Rah*_*jai 2 javascript setinterval iife
setInterval( function returnval(){
console.log('hello world');
return returnval;
}(),2000);
Run Code Online (Sandbox Code Playgroud)
首先,请记住我是 javascript 新手。有人可以解释这段让我困惑的代码吗?当我们在匿名 setInterval 中包含的 IIFE 函数中返回函数名称时,实际上发生了什么?还要提前谢谢你。
这是一种……有趣的……方法,可以立即运行函数,然后通过间隔计时器重复运行。:-)
在命名函数中,函数的名称是引用该函数的作用域内标识符。所以return returnval返回函数本身。
这是它的工作原理:
(),因此它会在结果传递到 之前立即setInterval执行。所以你马上就会看到“hello world”。setInterval设置为间隔计时器。以下是实现相同目标的稍微清晰的方法(包括不让函数名称出现在包含范围中):
// Use a scoping function to avoid creating a symbol in the
// containing scope (there are also other ways to do this)
(() => {
// Define it
function returnval() {
console.log("hello world");
}
// Call it immediately...
returnval();
// ...and also on an interval timer
setInterval(returnval, 2000);
})();
Run Code Online (Sandbox Code Playgroud)