gpt4 book ai didi

javascript - setInterval 内的 setTimeout 循环

转载 作者:行者123 更新时间:2023-11-27 22:40:46 24 4
gpt4 key购买 nike

我有类似的代码:

var count = 0;

setInterval(function() {
if(count===0){
console.log(123);
count++;
} else if(count>0) {
for(i=1;i<=2;i++){
(function(ind) {
setTimeout(function() {
console.log(ind);
}, 1000 * ind);
})(i);
}
count=0;
}
},1000)

结果不是我所期望的,我希望控制台日志实现的效果如下:

123
1
2
123
1
2
...

以此类推,每个间隔为 1000ms。另外我想问一下有没有更好的方法呢? setTimeout 循环的数量(上述情况为 2)每次可以/可能不同。

最佳答案

something like this, first print 123 and wait for 1000ms, then 1 and wait for 1000ms, finally 2 and wait for 1000ms after that repeat the whole process infinitely

如果您希望以 1000 毫秒的间隔定期执行,并进行内部倒计时然后重置,则可以仅使用单个 setInterval:

// Uses a 100ms rather than 1000ms counter, stopping after two seconds
var count = 0;
var inner = 0;
var handle = setInterval(function() {
if (inner == 0) {
// Start again
console.log(123);
count = 0;
// The number of "inner" counts to do
inner = 2;
} else {
// An "inner" count
++count;
--inner;
console.log(count);
}
}, 100);

// Stop it after two seconds, just for demo purposes
setTimeout(function() {
clearInterval(handle);
}, 2000);

关于javascript - setInterval 内的 setTimeout 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38762221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com