synchronous and asynchronous loops in javascript

后端 未结 5 1324
我在风中等你
我在风中等你 2020-12-14 06:43

Are loops synchronous or asynchronous in JavaScript? (for, while, etc)

Supposing I have:

for(let i=0; i<10; i++){
    // A (nested stuff...)
}

//         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 07:13

    First of all, your statement about "Using for the execution of B will start before A sometimes... (so asynchronous)" is wrong.

    The loop function (like while, for, .forEach or .map) in Javascript will be run synchronously (blocking), whether you run it in a Browser or Runtime Environment like NodeJS. We can prove it by running the code below (maybe the process will take a few seconds):

    let counter1 = 0
    let counter2 = 0
    let counter3 = 0
    
    console.log("Start iteration")
    console.time("Time required")
    
    // First heavy iteration
    for (let i = 0; i < 1000; i++) {
      counter1 += 1
    
      // Second heavy iteration
      for (let i2 = 0; i2 < 1000; i2++) {
        counter2 += 1
    
        // Third heavy iteration
        for (let i3 = 0; i3 < 1000; i3++) {
          counter3 += 1
        }
      }
    }
    
    console.log("Iteration was successful")
    console.timeEnd("Time required")
    console.log('The value of `counter1` is: ' + counter1)
    console.log('The value of `counter2` is: ' + counter2)
    console.log('The value of `counter3` is: ' + counter3)

    And then what kind of looping causes your code to run asynchronously (non blocking)?

    The answer is:

    The code that is placed inside the Promise callback or the function with the async keyword or some native functions with callback (not all) like setTimeout, setInterval and etc will be run asynchronously.

    Example:

    setTimeout(() => {
      console.log('A')
    })
    
    console.log('B')

    In code, setTimeout function is declared first. However, the output of the code shows that the console.log('B') function run earlier than the setTimeout function.

提交回复
热议问题