JavaScript Performance Long Running Tasks

setTimeout does not have a minimal delay of 0ms. The minimal delay is anywhere in the range of 5ms-20ms dependent on browsers.

My own personal testing shows that setTimeout doesn’t place your back on the event stack immediately

Live Example

It has an arbitary minimal time delay before it gets called again

var s = new Date(),
    count = 10000,
    cb = after(count, function() {
        console.log(new Date() - s);    
    });

doo(count, function() {
    test(10, undefined, cb);
});
  • Running 10000 of these in parallel counting to 10 takes 500ms.
  • Running 100 counting to 10 takes 60ms.
  • Running 1 counting to 10 takes 40ms.
  • Running 1 counting to 100 takes 400ms.

Cleary it seems that each individual setTimeout has to wait at least 4ms to be called again. But that’s the bottle neck. The individual delay on setTimeout.

If you schedule a 100 or more of these in parallel then it will just work.

How do we optimise this?

var s = new Date(),
    count = 100,
    cb = after(count, function() {
        console.log(new Date() - s);    
    }),
    array = [];

doo(count, function() {
    test(10, array, cb);
});

Set up 100 running in parallel on the same array. This will avoid the main bottleneck which is the setTimeout delay.

The above completes in 2ms.

var s = new Date(),
    count = 1000,
    cb = after(count, function() {
        console.log(new Date() - s);    
    }),
    array = [];

doo(count, function() {
    test(1000, array, cb);
});

Completes in 7 milliseconds

var s = new Date(),
    count = 1000,
    cb = after(1, function() {
        console.log(new Date() - s);    
    }),
    array = [];

doo(count, function() {
    test(1000000, array, cb);
});

Running a 1000 jobs in parallel is roughly optimum. But you will start hitting bottlenecks. Counting to 1 million still takes 4500ms.

Leave a Comment