2013-08-04 26 views
0

我在我的電臺網站上使用javascript歌曲倒計時。由於阿賈克斯調用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; 
?> 
+1

不要使異步調用同步;) – Andreas

+0

@Jeffman是正確的。如果你不需要它,刪除'async:false'(默認是一個隱含的'async:true')。 – ale

+0

謝謝!就是這樣。 – trogne

回答

4

我認爲async: false被劫持您的倒計時功能。你需要它是錯誤的嗎?

+0

哇!我懂了。現在沒有更多的滯後。感謝您的快速回復。 – trogne

+0

由於異步屬實,因此無法正常工作。往上看 – trogne

0
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);