我想每 n 秒后打印一次数字,并且根据一些条件我正在更改计时器以及停止打印功能。我已经这样做了——
var myfunc = {
value : 1,
running : false,
timer : 1000,
start : function(){
this.running = true;
clearInterval(this.timeout);
this.timeout = setTimeout(function() {
myfunc.execute(myfunc);
}, myfunc.timer);
},
execute : function(){
if(!this.running) return false;
console.log( 'Currently at -- ' + (this.value++) );
if (this.value > 5 ){
this.changetiming();
}
if (this.value > 10 ){
this.stop();
return;
}else{
this.start();
}
},
changetiming : function(){
this.timer = 3000;
},
stop : function(){
this.running = false;
clearTimeout(this.timeout);
}
};
myfunc.start();
现在我想知道以下代码有什么问题--
for(var i = 0; i <= 10; i++){
print(i);
}
function print(i){
setTimeout(function(){
console.log(i)
},2000);
}
这是在 ES6+ 中执行此操作的正确方法和简单方法:
const printNumbersForEvery2Sec = (n)=>{
for (let i = 1; i <= n; i++) {
setTimeout( () =>{
console.log(i)
}, i * 2000)
}
}
printNumbersForEvery2Sec(10);
通过乘法i
,每个 setTimeout() 分别延迟 2 到 20 秒(2000 x 1, 2000 x 2…)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)