Jaycee Liao Jaycee Liao - 4 years ago 116
Javascript Question

how to execute codes 1000 times in 1 second with javascript



n=0;
var timer= setInterval(function(){
if(n==0){
console.log(new Date());
}
//execute some other codes here
n++;
if(n==1000){
clearInterval(timer);
console.log(new Date());
}
},1);




after these codes are executed, it has been taking about 3-4 second according to different kind of machine or browser may be. So how can I execute some codes in 1 second ? Could anyone help me? Thanks

Answer Source

Javascript timers in browsers are inaccurate (C would be better for that usage).

However, you get a better averaged accuracy having the delay as high as possible, especially avoiding low values, like 1 ms.

It will be difficult to have 1000 evenly timed calls to a function, within one second. One millisecond being a low value , the simple execution of the triggered function itself (plus the overhead of handling timers) is likely to take a time close to 1 ms (or maybe more)... meaning the JS interpreter calls the function after 1ms, executes the code then set a new 1ms timer. Consequently there is more than 1ms between calls.

The JS interpreter does something like

At t   call function     <-- this takes
       execute function  <-- some 
at t+x set new 1ms timer <-- time
etc...

However if you can afford to end the process within a timeframe closer to 1 second (than the 3-4 seconds you have now), doing as many as possible 1 ms calls, this is possible.

var n = 0;

var timer= setInterval(function(){
          if(n++ == 0) {
                console.log(new Date());
          }
     }, 1);

setTimeout(function() {
         clearInterval(timer);
         console.log("Got n="+n+" at "+(new Date()));
     }, 1000);

This is basically the same program as yours

  • n is incremented every 1ms
  • however the end of the process is controlled by another 1-second timer

In Chrome, I get 252 n increments and the two dates are ~1 second apart.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download