【问题标题】:javascript countdown lagging because of ajax calls由于 ajax 调用,javascript 倒计时滞后
【发布时间】:2013-08-05 11:42:45
【问题描述】:

我在我的电台网站上使用 JavaScript 歌曲倒计时。

由于 ajax 调用检查是否有新歌,倒计时每 10 秒滞后一次(再跳 1 秒):

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;
?>

【问题讨论】:

  • 不要让异步调用同步;)
  • @Jeffman 是正确的。如果不需要,请删除 async: false(默认为隐式 async: true)。
  • 它不适用于 async = true。
  • 因为在我这样做之后:gcs = getcursong(); gcs 为空,因为 async=true。我能做什么?
  • 好的,我发现:function () { var result = null; var scriptUrl = "get_current_song.php"; $.ajax({ url: scriptUrl, type: 'get', dataType: 'html', async: true, success: function(data) { song = $('#song').html(); if (data ! = song && data != ""){ setTimeout(function (){ $('#nowplaying').load('nowplaying.php'); }, 5000); // pourquoi fadeIn("slow"); ?! ? } } }); }, 10000);

标签: php javascript ajax curl


【解决方案1】:

我假设async: false 正在劫持您的倒计时功能。你需要它是假的吗?

【讨论】:

  • 哇!我知道了。现在不再落后。感谢您的快速回复。
【解决方案2】:
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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多