简体   繁体   中英

setInterval function of javascript

In javascript we use setInterval functions like this.

myInteval= setInterval("func",t);

What if the execution time of "func" itself is greater than interval time t ?

I think js is single threaded. How is this achieved ??

Then it will wait until func has finished executing, check the queue of functions to run on an interval, then run it again.

See the event loop for more details.

A few important things from this piece by John Resig:

http://ejohn.org/blog/how-javascript-timers-work/

...timer delay is not guaranteed...

Which means, it is not essential that the t that you specify will be honoured as is. It indicates a minimum time and not a guaranteed time.

Further down:

...Intervals don't care about what is currently executing, they will queue indiscriminately, even if it means that the time between callbacks will be sacrificed...

So, effectively the func will be queued to be executed without any t delay if the queue is accumulated due to execution.

And is summarized at the end:

...Intervals may execute back-to-back with no delay if they take long enough to execute (longer than the specified delay).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM