Myt*_*ish 12 jquery loops 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);
}
Run Code Online (Sandbox Code Playgroud)
Mol*_*daa 19
试试看:
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);
Run Code Online (Sandbox Code Playgroud)
Don*_*ghn 13
如果你想要一个无限循环,你应该使用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);
Run Code Online (Sandbox Code Playgroud)
如果您以后决定需要停止重复代码,请在设置间隔时存储返回值并清除它:
var intervalId = setInterval(function() {
...
}, 1000);
clearInterval(intervalId);
Run Code Online (Sandbox Code Playgroud)