Shadi Shaaban
Shadi Shaaban

Reputation: 1720

Javascript setInterval execution in less than 1 ms?

I have this example that compares the performance of a simple counter loop using for loop and using setInerval, the exeuction time difference is huge as follows:

var i = 0;
var i2 = 0;
var int1 = null;

console.time("for loop");
do{  
  i++;
}while(i <= 1000);
console.timeEnd("for loop"); 


function fnc(){
  if(i2++ == 1000){
    clearInterval(int1);
    console.timeEnd("interval loop");
  }
}

console.time("interval loop");
int1 = setInterval(fnc , 1);

Outputs

enter image description here

See demo at: http://jsbin.com/jusiqilayi/edit?js,output

I would like to know if it is possible to execute a function using setInterval with a timespan less than 1ms? or is there a way to achieve better performance for the given example using setInterval?

Upvotes: 5

Views: 4721

Answers (1)

Ismail RBOUH
Ismail RBOUH

Reputation: 10450

setInterval and setTimeout are forced to use at least the minimum delay. The minimum delay, DOM_MIN_TIMEOUT_VALUE, is 4 ms which is specified by the HTML5 spec and is consistent across browsers released in 2010 and onward.

In modern browsers you can use window.postMessage() as a workaround to implement a 0 ms timeout as described here.

Upvotes: 9

Related Questions