繁体   English   中英

带箭头函数的 SetTimeout 递归

[英]SetTimeout recursive with arrow function

我想知道是否有一种方法可以使用带有箭头函数的 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)

这是因为箭头函数不会在箭头函数体内创建新的上下文,但普通函数会。 所以箭头函数中的 this 指的是父作用域上下文,但普通函数中的 this 指的是它自己的上下文。

可能最简单的方法是将箭头函数提取到它自己的变量中:

const run = () => {
    this.currentIndex++;
    console.log(this.currentIndex);
    setTimeout(run, 1000);
};
setTimeout(run, 1000);

尽管在这个特定示例中,您可以使用setInterval而不是setTimeout来进一步简化它,从而完全避免第二次setTimeout调用。

您可以先绑定this ,然后在所有调用中使用此函数。

function run(reference) {
    this.currentIndex++;
    console.log(this.currentIndex); // returns undefined
    setTimeout(reference, 1000, reference);
}

const runThis = run.bind(thisReference);

setTimeout(runThis, 1000, runThis);

这将递归地创建 setTimeouts

 let currentIndex = 0; const run = () => { setTimeout(() => { currentIndex++; console.log(currentIndex); run(); }, 1000); } run();

但更好的方法可能是(我不知道你的用例,所以它只是可能)使用setInterval()

 let currentIndex = 0; const interval = setInterval(() => { currentIndex++; console.log(currentIndex); // stop interval if (currentIndex >= 10) { clearInterval(interval); } }, 1000);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM