daremkd
daremkd

Reputation: 8424

setInterval and an event loop

Say I have some setInterval invocation with 10ms as an argument. I fire it up, and have some JavaScript code that takes 25ms to complete. After 10ms, the first interval callback is queued up. After 20ms, there's nothing additional queued up because (the Web API logic I presume, if this is where setInterval ticking occurs, decides this) one instance of a setInterval is already queued.

Now, at 25ms, when the main logic complete, setInterval starts and it takes, say, 10ms complete (so by the time it completes, 35ms would pass from program execution). At 30ms, while the setInterval callback is in the stack and executing, another tick occurs. What happens now? Will another instance of setInterval callback queue go in the event queue? Or will the browser environment see that there is an interval instance in the stack executing and skip pushing a new instance to the event queue, thus making the next setInterval instance tick at 40ms finally push a new callback?

Upvotes: 1

Views: 2790

Answers (1)

Hatchet
Hatchet

Reputation: 5428

As has been mentioned in the comments, JavaScript is single threaded. To demonstrate this, I tested this code:

var count = 0;
var interval = setInterval(function() {
    if (count >= 5) {
        clearInterval(interval);
        return;
    }

    var start = Date.now();
    var number = ++count;
    console.log("Call #" + number + " begin: " + start);

    // Delay for 250 ms
    while (Date.now() - start < 250) {}

    var end = Date.now();
    console.log("Call #" + number + " end: " + end + " Interval: " + (end - start));
}, 1);

And it outputs:

Call #1 begin: 1453087997262
Call #1 end: 1453087997512 Interval: 250
Call #2 begin: 1453087997522
Call #2 end: 1453087997772 Interval: 250
Call #3 begin: 1453087997777
Call #3 end: 1453087998027 Interval: 250
Call #4 begin: 1453087998027
Call #4 end: 1453087998277 Interval: 250
Call #5 begin: 1453087998277
Call #5 end: 1453087998527 Interval: 250

If JavaScript was multithreaded, the output would look more like:

Call #1 begin
Call #2 begin
Call #3 begin
Call #4 begin
Call #5 begin
// Approximate 245-250ms delay
Call #1 end Interval: 250
Call #2 end Interval: 250
Call #3 end Interval: 250
Call #4 end Interval: 250
Call #5 end Interval: 250

A JSFiddle to demonstrate: https://jsfiddle.net/Hatchet/126kkjwh/

Upvotes: 2

Related Questions