-1

I expect in following code setInterval runs 100 times before setTimeout.

var current = 0;

var timer = setInterval(function(){
    process.stdout.write(current.toString() + '\n');

    if(current === 1000) {
        clearInterval(timer);
        process.stdout.write('Done');   
    }

    current += 10;
}, 10);

setTimeout(function(){
    process.stdout.write('This is 1000.\n');
}, 1000);

But its the result:

860
870
880
This is 1000.
890
900
910
920
930
940
950
960
970
980
990
1000
Done

What I did not understand about setInterval? I think last setInterval and setTimeout should run together at the end.

Mohammad Ali Akbari
  • 10,345
  • 11
  • 44
  • 62
  • 1
    setInterval probably does its best to execute on the time you set, but since you run code in the interval it isn't guaranteed that it will execute and run exactly every 10ms as it will also take some small amount of time to run your code. JS isn't a real-time language. You can expect some diff in script execution time depending on HW/browser and current load on you machine as well – Peter Sep 28 '17 at 07:46
  • 1
    All the answers and the duplicated questions are not answer this question! The queue of nodejs should be far more fast than 10ms, and nodejs never says it will up round the interval to 10ms (which the browsers clearly state to be 4ms or something IIRC) – Todd Wong Nov 28 '21 at 05:17

3 Answers3

1

All scheduled code is put in a single queue and processed by one thread. If the setInterval function can't finish faster than 10ms, the execution time will fall behind the schedule. The precise time of execution cannot be guaranteed.

Gedrox
  • 3,592
  • 1
  • 21
  • 29
1

setInveral and setTimeout have no execution/scheduling guarantees and going down to as much as 10ms intervals will almost always fail. The best you can probably get for a predictable interval on browsers is requestAnimationFrame. That will usually match the refresh rate of the screen, so usually 16.66ms intervals for 60Hz. Keep in mind that this can still drop frames and it may get suspended if the tab is not in focus.

Aurelia
  • 1,052
  • 6
  • 28
0

Maybe because the process.stdout.write which is a consumming I/O operation takes more than 10ms.

setInterval() is waiting the function to finish before to start an other one.

Orelsanpls
  • 22,456
  • 6
  • 42
  • 69