我在电台网站上使用javascript歌曲倒计时。
每10秒,倒计时就会滞后(再跳过1秒),因为ajax调用检查是否有新歌:
function getcursong(){
var result = null;
var scriptUrl = "get_current_song.php";
$.ajax({
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
在控制台中,我看到GET
调用大约需要2秒钟。
get_current_song.php
使用curl
从icecast服务器获取当前歌曲。
我能做些什么来防止倒计时因为那些ajax调用而滞后吗?
下面是get_current_song.php
。
<?php
require('config.php');
$current_song = getStreamInfo();
function url_get_contents($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_TIMEOUT,2);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
function getStreamInfo(){
$str = url_get_contents(SERVER.'/status.xsl?mount='.MOUNT);
if(preg_match_all('/<td's[^>]*class='"streamdata'">(.*)<'/td>/isU', $str, $match)){
$x = explode(" * ",$match[1][9]);
return $x[1];
}
}
?>
<?php
echo $current_song;
?>
我假设async: false
正在劫持您的倒计时功能。你需要它是假的吗?
function ()
{
var result = null;
var scriptUrl = "get_current_song.php";
$.ajax({
url: scriptUrl,
type: 'get',
dataType: 'html',
async: true, // NEEDED TO BE TRUE
success: function(data) { // on success, I get the data
song = $('#song').html();
if (data != song && data != ""){
setTimeout(function (){ $('#nowplaying').load('nowplaying.php'); }, 5000); // pourquoi fadeIn("slow"); ?!?
}
}
});
}, 10000);