简体   繁体   English

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

[英]setTimeout with IIFE is NOT asynchronous?

I've found a strange behavior in the following JavaScript code: 我在以下JavaScript代码中发现了一个奇怪的行为:

 console.log('hi') setTimeout(function(){ console.log('there'); }(), 5000) console.log('I am js'); 

My expected output in the console is: 我在控制台中的预期输出是:
hi
I am js 我是js
there 那里

But it is showing me: 但这向我展示了:
hi
there 那里
I am js 我是js

Why is that? 这是为什么? If we use an IIFE with setTimeout it does not go through event loop and tasks queue? 如果我们将IIFE与setTimeout一起使用,它不会通过事件循环和任务队列吗? Could anyone explain the above output? 谁能解释上面的输出? Thanks in advance. 提前致谢。

When you define the function, you are executing it in the same step, thus the console log is displayed. 定义功能时,将在同一步骤中执行它,因此将显示控制台日志。

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

In this case, the argument that setTimeout() receives is the function return value, which is undefined in this case. 在这种情况下, setTimeout()接收的参数是函数返回值,在这种情况下undefined

I read your code as: 我将您的代码读取为:

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');

Now, if you had returned another function, it would execute in 5 seconds as expected. 现在,如果您返回了另一个函数,它将按预期在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'); 

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

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