What will the following JavaScript code output?for (var i = 0; i < 3; i++) { setTimeout(function() { alert(i); }, 1000 + i);}
Question
What will the following JavaScript code output?
for (var i = 0; i < 3; i++) {
setTimeout(function() {
alert(i);
}, 1000 + i);
}
Solution
The given JavaScript code will output the number 3 three times, with a delay of 1000 milliseconds for each alert.
Here's a step-by-step breakdown of what happens:
- The code starts with a for loop that initializes a variable
i
to 0. - The loop condition checks if
i
is less than 3. Since 0 is less than 3, the loop proceeds. - Inside the loop, a setTimeout function is called. This function takes two arguments: a callback function and a delay time.
- The callback function passed to setTimeout is an anonymous function that alerts the value of
i
. - The delay time for each setTimeout call is calculated as 1000 +
i
. In the first iteration, the delay is 1000 milliseconds. - After the setTimeout function is called, the loop increments
i
by 1. - The loop condition is checked again. Since
i
is now 1, which is less than 3, the loop proceeds to the next iteration. - The same process is repeated for the second and third iterations of the loop.
- After the third iteration,
i
becomes 3, which is not less than 3. The loop condition fails, and the loop terminates. - The setTimeout functions start executing their callback functions after the specified delays. However, since the loop has already finished executing, the value of
i
is 3 for all the callback functions. - As a result, when the alert function is called inside each callback function, it will display the value 3 three times.
Therefore, the output of the given JavaScript code will be three alert boxes displaying the number 3.
Similar Questions
How many times will the following loop runfor(c = 1; c < 20; c=c+5) {document.write("C : " + c );document.write("<br />");
What is the output of following code?var a = 10;function test() { a = 20;}test();console.log(a);Options: Pick one correct answer from below1020
What will be the output of the following code snippet?var a = 1; var b = 0; while (a <= 3) { a++; b += a * 2; print(b); }*4 10 181 2 3None of Above1 4 7
What is the output of this code?const a = 12;function myFunction(a) { console.log(a);}myFunction(89);112289
Which function is used to schedule a function to be executed after a specified delay in JavaScript?OptionssetTimeout()setDelay()wait()setInterval()
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.