我想知道是否有办法使用箭头函数实现递归的setTimeout,并且可以在其中使用 this
(例如,引用我的类属性)。实际上,当我使用普通函数声明我的setTimeout时,this = undefined
。
我得到:
public currentIndex: number = 0;
setTimeout(function run(){
this.currentIndex++;
console.log(this.currentIndex); // returns undefined
setTimeout(run, 1000);
}, 1000)
改为:
setTimeout(() => {
this.currentIndex++;
console.log(this.currentIndex) // returns currentIndex value
setTimeout( ?? , 1000) // What should i put instead of '??' ?
}, 1000)
setInterval
来执行递归任务?https://developer.mozilla.org/en-US/docs/Web/API/setInterval - Himanshu AggarwalsetInterval
似乎不适用于我的情况。 - Fab83iawait
在迭代之间暂停的循环,例如for(;;await delay(1000)){ this.currentIndex++; }
。 - Thomas