jQuery - 可变区间

jQuery - variable interval

这是我当前的代码:

$(document).ready( function() {

// set variables
var delay = 3000;

setInterval( function() {

    // perform AJAX call
    var req = $.ajax({
        url: "view/jquery/jq.refresh.php",
        dataType: "json"
    });

    // process data from json
    req.done( function(data) {
        $("#now_playing").html(data.song);
        $("#queue_list").html(data.queue);

        delay = data.time;
    });        

}, delay);
});

...它没有按计划工作。

我们的想法是使用 AJAX 从数据库中检索可变延迟(歌曲的长度)。并将该延迟(歌曲的长度)放入 setInterval,这样脚本将根据正在播放的歌曲的长度以可变间隔循环,希望减少 server/database 负载。

我确定从数据库中检索到正确的延迟值,因为添加 console.log(date.time); 显示了歌曲的长度。

我认为我的代码无法运行的一个理论是 setInterval 在实际处理其中的代码之前读取其 ms 值,因此它始终设置为 3000。 另一种理论是 delay = data.time 不会更改 delay 值,因为它是在脚本开头设置的全局变量。

那么在没有 crashing/freezing 浏览器的情况下,我有什么选择可以实现可变间隔?

setInterval reads its ms value before actually processing the code within, so it's always set to 3000

是的。您只调用 setInterval 一次,同时 delay 设置为 3000。在那之后更改 delay 的值不会影响已经安排的间隔。

如果你想要一个可变区间,你不能使用setInterval。使用 setTimeout,并让每个回调将其后续回调排队。

function pollNext() {
    // perform AJAX call
    var req = $.ajax({
        url: "view/jquery/jq.refresh.php",
        dataType: "json"
    });

    // process data from json
    req.done( function(data) {
        $("#now_playing").html(data.song);
        $("#queue_list").html(data.queue);

       setTimeout(pollNext, data.time);
    });     

}

pollNext(); // Prime the initial invocation

因为在初始调用 setInterval 时设置了间隔。修改 delay 的值将没有效果。

在这种情况下您应该使用 setTimeout

$(document).ready(function() {
    // set variables
    var delay = 3000;

    //Define a function
    function getData() {

        // perform AJAX call
        var req = $.ajax({
            url: "view/jquery/jq.refresh.php",
            dataType: "json"
        });

        // process data from json
        req.done(function(data) {
            $("#now_playing").html(data.song);
            $("#queue_list").html(data.queue);

            delay = data.time;
            //Schedule the subsequent execution 
            setTimeout(getData, data.time);
        });
    }

    //Schedule to execute after 3 seconds on page load
    setTimeout(getData, delay);
});

setInterval() 的调用的 delay 仅在声明间隔时读取一次。您在实例化后尝试更改 delay 变量将无效。

另一种方法是链接 setTimeout() 调用,这样您就可以更改下一次超时的延迟。试试这个:

function createTimeout(delay) {
    setTimeout(function() {   
        $.ajax({
            url: "view/jquery/jq.refresh.php",
            dataType: "json"
        }).done(function(data) {
            $("#now_playing").html(data.song);
            $("#queue_list").html(data.queue);
            createTimeout(data.time);
        });            
    }, delay);
}

createTimeout(3000);