简体   繁体   English

函数结果出现在for循环执行之前

[英]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

console result 控制台结果

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; 因此您的代码更像是这样;

  1. Put five 'timer' functions in the queue. 将五个“定时器”功能放入队列。 Each one must wait 1s, 2s, 3s, etc before it's executed, and each must execute after the current block. 每个执行之前必须等待1、2、3等,并且每个都必须在当前块之后执行。
  2. Execute the 'CoolModule' code. 执行“ CoolModule”代码。
  3. (the code you wrote finishes executing) (您编写的代码完成执行)
  4. (wait 1s) (等待1秒)
  5. run the first instance of timer() 运行timer()的第一个实例
  6. (wait another 1s) (再等待1秒)
  7. run the second instance of timer() 运行timer()的第二个实例
  8. etc... 等等...

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

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