How to run an operation for exactly x seconds in javascript?

Abh*_*hek 0 javascript

I've following code,

console.time("a");
var i = 0;
var intervalID = setInterval(function () {
    i++;
    if( i == 100){
        window.clearInterval(intervalID);
        console.timeEnd("a");
    }
}, 1);
Run Code Online (Sandbox Code Playgroud)

It outputs following,

a: 389.15380859375ms

Generally, the code runs for more than 100 ms. But if you see the code, the code should have been completed in 100ms, atleast I was expecting it to run in 100 ms. I'm okay with 100 +/- 10 ms, but the output is 3 times, which is unacceptable for my use-case. Basically, I want to run a operation for 100 ms, above code is just a sample. So, what am I missing? How do I run the code precisely for 100 ms?

Mar*_*tin 5

The setInterval method has a minimum working value of 4ms. This is described here.

If I produce the same code but with 10 x 10ms intervals, you get close to 100ms:

console.time("a");
var i = 0;
var intervalID = setInterval(function () {
    i++;
    if( i == 10){
        window.clearInterval(intervalID);
        console.timeEnd("a");
    }
}, 10);
Run Code Online (Sandbox Code Playgroud)

It's worth noting that setInterval may not be precise. Look:

In addition to "clamping", the timeout can also fire later when the page (or the OS/browser itself) is busy with other tasks

You cannot guarantee that you will get exactly 100ms with setInterval.