jQuery 如何创建一个简单的 setTimeout 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8080983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 09:58:51  来源:igfitidea点击:

How to create a simple setTimeout loop

jqueryloopssettimeout

提问by Mythical Fish

I simply need to create an infinite loop through 3 variations of an element. This is what I have so far:

我只需要通过一个元素的 3 个变体来创建一个无限循环。这是我到目前为止:

    var count = 1;
    setTimeout(transition, 2000);

    function transition() {

        if(count == 1) {
            $('#ele').html('variation 2');
            var count = 2;

        } else if(count == 2) {
            $('#ele').html('variation 3');
            var count = 3;

        } else if(count == 3) {
            $('#ele').html('variation 1');
            var count = 1;
        }

        setTimeout(transition, 2000);

    }

回答by Molochdaa

try that :

试试看:

var count = 1;

function transition() {

    if(count == 1) {
        $('#ele').html('variation 2');
         count = 2;

    } else if(count == 2) {
        $('#ele').html('variation 3');
         count = 3;

    } else if(count == 3) {
        $('#ele').html('variation 1');
        count = 1;
    }

}
setInterval(transition, 2000);

回答by DonVaughn

If you want an infinite loop, you should be using setInterval(). This will run an infinite loop, each time running the next variation:

如果你想要一个无限循环,你应该使用setInterval(). 这将运行一个无限循环,每次运行下一个变体:

var i=0;

setInterval(function() {
    switch(i++%3) {
        case 0: alert("variation 1");
        break;
        case 1: alert("variation 2");
        break;
        case 2: alert("variation 3");
        break;
    }

}, 2000);

If you later decide you need to stop the repeating code, store the return value when you set the interval and clear it:

如果您稍后决定需要停止重复代码,请在设置间隔时存储返回值并清除它:

var intervalId = setInterval(function() {
    ...
}, 1000);

clearInterval(intervalId);

回答by Andres Separ

This is the best solution:

这是最好的解决方案:

The clearTimeout()method clears a timer set with the setTimeout()method.

所述clearTimeout()方法清除一个定时器设定与所述的setTimeout()方法。

(function(){
    var timer, count=1;
    function transition(){
        clearTimeout(timer);

        switch(count){
            case 1: count = 2; break;
            case 2: count = 3; break;
            case 3: count = 1; break;
        }

        $('#ele').html('variation ' + count);

        timer = setTimeout(transition, 2000);
    }
    transition();
})();

回答by Mohamed Abulnasr

My best way in real life jobs is to "Forget Basic Loops"in this case and use this combination of "setInterval" includes "setTimeOut"s:

在现实生活中,我最好的方法是在这种情况下“忘记基本循环”并使用“setInterval”的这种组合包括“setTimeOut”:

    function iAsk(lvl){
        var i=0;
        var intr =setInterval(function(){ // start the loop 
            i++; // increment it
            if(i>lvl){ // check if the end round reached.
                clearInterval(intr);
                return;
            }
            setTimeout(function(){
                $(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
            },50);
            setTimeout(function(){
                 // do another bla bla bla after 100 millisecond.
                seq[i-1]=(Math.ceil(Math.random()*4)).toString();
                $("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
                $("#d"+seq[i-1]).prop("src",pGif);
                var d =document.getElementById('aud');
                d.play();                   
            },100);
            setTimeout(function(){
                // keep adding bla bla bla till you done :)
                $("#d"+seq[i-1]).prop("src",pPng);
            },900);
        },1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
    }

PS: Understand that the real behavior of (setTimeOut): they all will start in same time "the three bla bla bla will start counting down in the same moment" so make a different timeout to arrange the execution.

PS:理解(setTimeOut)的真实行为:它们都会在同一时间开始“三个bla bla bla将在同一时刻开始倒计时”,因此请使用不同的超时来安排执行。

PS 2: the example for timing loop, but for a reaction loops you can use events, promise async await ..

PS 2:计时循环的示例,但对于反应循环,您可以使用事件,promise async await ..

回答by Bashirpour

$(document).ready(function () {
    $("[data-count]").each(function () {
        counter($(this), .5)
    });

    function counter(el, speed) {
        let number = el.data("count"),
            count_type = el.data("count-type"),
            i = count_type === "up" ? 0 : number;

        let inter_val = setInterval(function () {
            el.text(i);
            i = count_type === "up" ? i + 1 : i - 1;
            if ((count_type === "up" && i > number) || (count_type === "down" && i < 0))
                clearInterval(inter_val);
        }, speed);
    }
});
span {
    background-color: #eeeeee;
    color: #333;
    padding: 15px 25px;
    margin: 10px;
    display: inline-block;
    width: 100px;
    text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>COUNT UP EXAMPLE</p>
<span data-count="1650" data-count-type="up"></span>
<span data-count="2500" data-count-type="up"></span>
<span data-count="985" data-count-type="up"></span>
<br>
<p>COUNT DOWN EXAMPLE</p>
<span data-count="1650" data-count-type="down"></span>
<span data-count="2500" data-count-type="down"></span>
<span data-count="985" data-count-type="down"></span>

回答by Jim H.

You have varin front of your countvariable inside the transitionfunction. Remove them and the outer countvariable will hold its value.

var在函数count内部的变量前面transition。删除它们,外部count变量将保持其值。

回答by Gholamreza Fathpour

if you still want to use setTimeoutand clearTimeoutto create a loop you should use something like this structure for your loop

如果你仍然想使用setTimeoutclearTimeout来创建一个循环,你应该为你的循环使用类似这样的结构

var count = 1;
var timer = setTimeout( function(){
    transaction();
} , 2000);

function transition() {

    if(count == 1) {
        $('#ele').html('variation 2');
        count = 2;

    } else if(count == 2) {
        $('#ele').html('variation 3');
        count = 3;

    } else if(count == 3) {
        $('#ele').html('variation 1');
        count = 1;
    }
    //if(condition for continue) 
    setTimeout(transition, 2000);
    //else if you want to stop the loop
    //clearTimeout(timer, 2000);
}