使用IIFE的setTimeout不是异步的吗?

时间:2017-04-13 01:17:10

标签: javascript jquery

我在以下JavaScript代码中发现了一个奇怪的行为:

console.log('hi')

setTimeout(function(){
  console.log('there');
}(), 5000)

console.log('I am js');

我在控制台中的预期输出是:
你好 我是js
那里

但它告诉我:
你好 有 我是js

为什么?如果我们使用带有setTimeout的IIFE,它不会经历事件循环和任务队列?有谁可以解释上面的输出?提前致谢。

1 个答案:

答案 0 :(得分:3)

定义该功能时,您将在同一步骤中执行该功能,从而显示控制台日志。

function(){
  console.log('there');
}()

在这种情况下,setTimeout()收到的参数是函数返回值,在这种情况下为undefined

我将您的代码读作:

console.log('hi')

var arg = function(){ console.log('there') }(); // arg receives undefined

setTimeout(arg, 5000) // where arg is undefined and not a function

console.log('I am js');

现在,如果您返回了另一个函数,它将按预期在5秒内执行。



console.log('hi')
    
var arg = function(){ 
  console.log('there') 
  
  return function() {
     console.log('there again') 
  }
  
}(); // arg receives a function
    
setTimeout(arg, 5000) // where arg is a function
    
console.log('I am js');




相关问题