2016-08-03 42 views
0

這裏是我當前的代碼:jQuery的 - 可變間隔

$(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,這樣腳本會根據正在播放的歌曲長度以可變間隔循環播放,希望可以減少服務器/數據庫負載。

我確定從數據庫中檢索到延遲的正確值,因爲添加console.log(date.time);可以顯示歌曲的長度。

一個理論,我有爲什麼我的代碼將無法工作,setInterval在實際處理代碼之前讀取其ms值,因此它總是設置爲3000。 另一個理論是delay = data.time不會更改delay值,因爲它是在腳本開始處設置的全局變量。

那麼我有什麼選擇來實現可變間隔而不會崩潰/凍結瀏覽器?

回答

1

由於最初調用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); 
}); 
0

的setInterval讀取它的MS值之前實際中處理的代碼,所以它總是設置爲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 
0

通話的delaysetInterval()是隻讀一次。在實例化後更改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);