Are loops synchronous or asynchronous in JavaScript? (for, while, etc)
Supposing I have:
for(let i=0; i<10; i++){
// A (nested stuff...)
}
//
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
Promisecallback or thefunctionwith theasynckeyword or some native functions with callback (not all) likesetTimeout,setIntervaland etc will be run asynchronously.
Example:
setTimeout(() => {
console.log('A')
})
console.log('B')
In code,
setTimeoutfunction is declared first. However, the output of the code shows that theconsole.log('B')function run earlier than thesetTimeoutfunction.