简体   繁体   English

返回 setInterval 中使用的 IIFE function

[英]Returning inside an IIFE function used in setInterval

setInterval( function returnval(){
  console.log('hello world');
  return returnval;
}(),2000);

First of all, keep in mind that I am new to javascript. Can someone please explain this given piece of code that is confusing me?首先,请记住我是 javascript 的新手。有人可以解释这段让我困惑的代码吗? What is actually happening when we return the function name inside an IIFE function contained inside an anonymous setInterval?当我们返回匿名 setInterval 中包含的 IIFE function 中的 function 名称时,实际发生了什么? And also thank you in advance.也提前谢谢你。

That's an...interesting...approach to running a function right away and then repeatedly via an interval timer.这是一种......有趣的......立即运行 function 然后通过间隔计时器重复运行的方法。 :-) :-)

Within a named function, the function's name is an in-scope identifier referring to the function. So return returnval returns the function itself.在命名的 function 中,函数的名称是引用 function 的范围内标识符。因此return returnval返回 function 本身。

Here's how that's working:这是它的工作原理:

  • The function expression creating the function is followed by () , so it's executed immediately , before the result is passed into setInterval .创建 function 的 function 表达式后跟() ,因此它会在结果传递到setInterval之前立即执行。 So you see "hello world" right away.所以你马上就会看到“hello world”。
  • Then since the function returns itself, it is passed into setInterval to be set up as an interval timer.然后由于 function 返回自身,它被传递到setInterval以设置为间隔计时器。
  • A couple of seconds later, the browser calls the function again (ignoring its return value), showing "hello world" again, and keeps doing that until/unless the interval timer is cancelled.几秒钟后,浏览器再次调用 function(忽略其返回值),再次显示“hello world”,并一直这样做直到/除非取消间隔计时器。

Here's what might be a slightly clearer way to achieve the same thing (including not having the function name appear in the containing scope):下面是实现相同功能的更清晰的方法(包括不让 function 名称出现在包含范围中):

// 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);
})();

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

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