Richard
Richard

Reputation: 135

JavaScript execution order of setTimeout() callbacks with different delays

If multiple callbacks are registered at the same time, is it guaranteed that the first callback to be called will be the one with the least delay?

Consider the following code:

function foo(i) {
    setTimeout(function () {
        console.log(i);
    }, i);
}

for (var i = 0; i < 1000; i++) {
    foo(i);
}

Is this code guaranteed to output 1-1000 in order?


Please note: This question is not about using equal delays. It has been established that multiple setTimeout() calls with equal delays are not guaranteed to execute in order.

Upvotes: 1

Views: 1083

Answers (2)

Rudra
Rudra

Reputation: 1688

I know many of the people have already answered this question. But, most of the people don't know exactly how the event loop works. Even I got it recently. So, I thought it would be helpful to all whoever gets to this post.

setTimeout() function works in accordance with the event callback and render queue. Rendering queue is the reason why it is not guaranteed that your callback would execute after the exact timeout. There are concepts like

  1. call stack,
  2. web apis and
  3. callback queue

You have this below function called multiple times,

function foo(i) {
    setTimeout(function () {
        console.log(i);
    }, i);
}

so the flow would be something like, each call to foo(i) would first go to call stack. Once the call stack reaches to its top (when loop is over), one by one the web api(browser specific)would handle the poped out function from the stack and then it moves to the callback queue when the timeout has reached. Depending on the availability that is, if rendering is not happening, the callback gets executed.

Inside the callback queue the functions are lined up in the order of calling.

So, the order is guaranteed.

A better place to understand the event queue is the below article.

Philip Roberts: What the heck is the event loop?

Upvotes: 0

Anand Singh
Anand Singh

Reputation: 2363

Yes!!

function foo(i) {
    setTimeout(function () {
        console.log(i);
    }, i);
}

for (var i = 1; i <= 1000; i++) {
    foo(i);
}

Explanation :

As you are Calling setTimeout it will execute independently doesn't matter how much setTimeout are running or will run,So its dependent on time you call and timing you set.Hope you get this.

Upvotes: 2

Related Questions