javascript - 立即调用的函数表达式 (iife) 如何作为 setTimeout 的参数工作

标签 javascript

谁能帮我理解为什么返回的函数会被执行?

const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
  setTimeout(function(i_local) {
    //The function below is just returned and not called using '()', so why is it executed? Why does the console.log works?
    return function() {
      console.log('The index of this number is: ' + i_local);
    }
  }(i), 3000);
}

最佳答案

setTimeout 函数获取一个函数作为参数,并在 X 毫秒后执行它。

在 JavaScript 中,函数就像任何其他变量一样。您可以将它们作为参数传递给其他函数。其他函数可以稍后执行。

像这样:

function setNow(func){
    func()
}

setNow(function(){
    console.log('this will be executed.')
})

同样,即使您不使用 () 直接调用该函数,该函数也会被执行。

在您的示例中,您的内部函数返回,现在这是 setTimeout 接收的函数。它将在 X 毫秒后执行。

我建议您以不同的方式进行操作:

const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
  setTimeout( (i_local=> {
      console.log('The index of this number is: ' + i_local);
  }).bind(this,i), 3000);
}

了解更多:

关于javascript - 立即调用的函数表达式 (iife) 如何作为 setTimeout 的参数工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48252525/

相关文章:

javascript - 如何允许在内部 Windows 身份验证 Intranet 上上传多个文件?

javascript - React.js 传递 => Prop

javascript - 如果我为同一事件设置 "listenToOnce"多次触发会发生什么

javascript - 在哪里可以找到 Javascript 的 `string.replace(RegExp, function)` 方法的文档?

javascript - 当用户滚动时更改 div 的不透明度

javascript - 通过多个页面的 FireBreath 插件

javascript - 在 iis7 上浏览应用程序时找不到 css 和 js 文件(服务器响应状态为 404)

javascript - Protractor - 通用等待 URL 更改

javascript - Chosen.js 性能

JavaScript 错误监听器