[英]Function results appears before for loop executes
My question is: why function results appears before for loop in browser console? 我的问题是:为什么函数结果出现在浏览器控制台的for循环之前? It should run for loop (1, 2, 3, 4, 5), but it run ('cool' and 1!2!3) first, so below I add my code and console result.
它应该为循环(1、2、3、4、5)运行,但是首先运行(“ cool”和1!2!3),因此下面我添加了代码和控制台结果。 I'll be very thankful if someone can explain me this behaviour.
如果有人可以向我解释这种行为,我将非常感激。 It is not a duplicate, because, I want to understand how it works, not to make it work.
它不是重复的,因为我想了解它是如何工作的,而不是使其工作。 In suggested question there is a solutions to run for loop with setTimeout first, but not explain behaviour completely.
在建议的问题中,有一个解决方案要首先使用setTimeout进行循环,但不能完全解释行为。
// Loops + Closure
for (let i = 1; i <= 5; i++) {
setTimeout(function timer() {
console.log(i)
}, i * 1000)
}
//Modules
function CoolModule() {
let something = 'cool'
let another = [1, 2, 3]
function doSomething() {
console.log(something)
}
function doAnother() {
console.log(another.join('!'))
}
return {
doSomething: doSomething,
doAnother: doAnother
}
}
let foo2 = CoolModule()
foo2.doSomething() // 'cool'
foo2.doAnother() // 1 ! 2 ! 3
JavaScript works by running blocks of code one after the other. JavaScript通过一个接一个地运行代码块来工作。 So you have one block of code that starts with the
for
loop and ends with foo2.doAnother()
. 因此,您有
foo2.doAnother()
代码以for
循环开头,以foo2.doAnother()
结尾。 But the calls to setTimeout
don't run the code immediately -- they put new blocks of code in the queue -- the console.log(i)
blocks. 但是对
setTimeout
的调用不会立即运行代码-它们会将新的代码块放入队列中console.log(i)
块。 So your code works more like; 因此您的代码更像是这样;
timer()
timer()
的第一个实例 timer()
timer()
的第二个实例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.