Practice problem js

setTimeout(() => {
for (let i = 0; i <= 5; i++) {
console.log(i);
}
}, 1000);

OUTPUT

2 Likes

@atulfebe
0
1
2
3
4
5
The timeout ensures that the loop is executed after a delay of 1 second. Therefore, the output will appear in the console after a delay of 1 second.

So you are saying Execution context in call stack mapped 6 set of setTimeout function which sent to web Api for running in background?@rrnayak2609

1 Like

Yes, that’s correct. When the setTimeout function is called, it schedules the execution of the inner function after the specified delay time (in this case, 1000 milliseconds or 1 second). The setTimeout function itself returns a unique identifier for the scheduled task.

When the JavaScript engine encounters the setTimeout function call, it creates an execution context for that function and adds it to the call stack. However, since the function is asynchronous, the engine immediately moves on to the next line of code without waiting for the scheduled task to complete.

Instead, the scheduled task is sent to the browser’s Web API, which handles the delay time in the background. Once the delay time has elapsed, the Web API sends the completed task to the task queue.

When the call stack is empty (i.e., all synchronous tasks have completed), the event loop checks the task queue for completed tasks. If there are any tasks in the queue, it moves them to the call stack for execution. In this case, the inner function passed to setTimeout is executed, which prints the numbers 0 through 5 to the console.

Yeah scheduling the inner function for 1 second delay to execute does not mean the for loop iterate after every 1 second ,it will execute immediately after 1second and log the value 0 to 5 without any delay @ rrnayak2609

1 Like