簡體   English   中英

JS無限循環

[英]JS infinite loop

我如何在下面的 JS 上設置無限循環? 在底部,它有一個以 50 秒運行的計時器,我需要它每 50 秒運行一次。 我的 JS 知識是 0%。 我什至不知道下面發生了什么,盡管向我解釋了其中的一些,所以非常小但模糊的理解。

//an array for later use at line 30 and line 35.
var classnames = ["one","two","three","four","five","six"];

//Used css3 selector for class (".classname") 
var elements = document.querySelectorAll(".ani");

setTimeout(function() {
for (var i=0; i<elements.length; i++) {
var element = elements[i];

//e.g elements[0] removes class "one", elements[1] removes "two"
element.classList.remove(classnames[i]);

element.offsetWidth = element.offsetWidth;

//e.g elements[0] adds class "one", elements[1] adds "two"
element.classList.add(classnames[i]);
}
}, (50*1000));

我不明白你想用你正在使用的元素來完成什么,但我不會管它,因為它超出了你的問題的直接范圍。

看看如何每 50 秒運行一次的問題,很多人會推薦setinterval 但是,我建議您堅持使用setTimeout並調整您的代碼以遞歸運行(在 setTimeout 中再次從其內部調用該函數)。

我提供這個替代方案是因為setInterval將繼續排隊調用您的代碼,即使您的代碼中的某些內容需要一段時間並且尚未完成。 這可能會導致競爭條件、性能停滯等。通過使用setTimeout我們可以確保在安排新的運行之前已完成運行。

這是您修改后的代碼以執行我的建議:

var classnames = ["one","two","three","four","five","six"],
    elements = document.querySelectorAll(".ani"),
    // put the logic into a function which we can call
    cycler = function () {
        var i,
            c = elements.length,
            element;

        for (i = 0; i < c; i++) {
            // your original element manipulation code, odd as it may be
            element = elements[i];

            element.classList.remove(classnames[i]);
            element.offsetWidth = element.offsetWidth;

            element.classList.add(classnames[i]);
        }

        // queue up another run
        cycle_timer = setTimeout(cycler, 50*1000);
    },
    //somewhere to store the return of setTimeout so we can stop it if we want
    cycle_timer = null;

// start it up!
cycler();

// if you want to stop it:
clearTimeout(cycle_timer);
setInterval(function() {
  // do your stuff here
}, 50*1000);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM