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

我只需要通过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); } 

试试看:

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

如果你想要一个无限循环,你应该使用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); 

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

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

这是最好的解决方案:

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(); })(); 

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

如果你仍然想使用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); } 

我在现实生活中最好的工作方式是在这种情况下“忘记基本循环”并使用“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('
'+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:理解(setTimeOut)的真实行为:它们都会在同一时间开始“三个bla bla bla将在同一时刻开始倒计时”,所以要做出不同的超时来安排执行。

PS 2:定时循环的示例,但对于反应循环,您可以使用事件,承诺异步等待..