返回 setInterval 中使用的 IIFE 函数内部

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 函数中返回函数名称时,实际上发生了什么?还要提前谢谢你。

T.J*_*der 6

这是一种……有趣的……方法,可以立即运行函数,然后通过间隔计时器重复运行。:-)

在命名函数中,函数的名称是引用该函数的作用域内标识符。所以return returnval返回函数本身。

这是它的工作原理:

  • 创建函数的函数表达式后面跟着(),因此它会在结果传递到 之前立即setInterval执行。所以你马上就会看到“hello world”。
  • 然后,由于该函数返回自身,因此将其传递给setInterval设置为间隔计时器。
  • 几秒钟后,浏览器再次调用该函数(忽略其返回值),再次显示“hello world”,并继续执行此操作,直到/除非间隔计时器被取消。

以下是实现相同目标的稍微清晰的方法(包括不让函数名称出现在包含范围中):

// 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)