setTimeout vs setInterval again

前端 未结 2 530
情深已故
情深已故 2021-01-21 05:46

So I know that there are differences between setTimeout and setInterval, but consider these two code examples:

function myFunction(){
          


        
2条回答
  •  说谎
    说谎 (楼主)
    2021-01-21 06:50

    T.J. Crowder explained the main differences, one other more subtle could appear (I change the time scale as it's easier to explain) :

    Lets plot the difference with a very big timeout time : 1 Day. You call both methods at 00:00 on Day 1 and let it run for 1 year...

    1 Year latter your method called by setInterval will execute at 00:00 + some milliseconds (because you may not be the only one asking for the processors to do things at this exact moment and the OS timers have granularity anyway).

    But your setTimeout method will occur latter, maybe around 00:01 because each day it would have been called a little after the requested time and requested to be called the next day at the same time...

    PS: It could also be called before the requested time in some cases but more often than not it run after :-D

提交回复
热议问题