setInterval() behaviour with 0 milliseconds in JavaScript

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-26 20:49:28

Browser set a minimal value for the interval. Usualy 10ms, but it can depend on the browser. This means repeat this as fast as I'm possibly allowed. The W3C spec say 4ms : http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#timers

This is correct but probably reveal a design error.

EDIT: By the way, it is bad practice to pass a string to setTimeout/setInterval, pass a function instead as javascript has first class functions.

Narendra Yadala

setInterval(myFunction, 0) calls myFunction continuously with minimum delay. It is almost like calling myFunction in a infinite loop. Except that here you can stop the loop using the clearInterval method.

To have it executed only once with minor delay, use setTimeOut instead:

window.setTimeout(myFunction, 10);

As you're using AJAX, you don't have to use any timers at all - just call the next AJAX request in the Callback (complete/success event) of the current AJAX request.

Post your current code and we might be able to guide you further.

I assume that in myFunction() there is a clearInterval.

Basically, you've set an interval that can happen as often as possible. If the browser executing JavaScript actually gets to the clearInterval part before the next iteration of the interval, then it will be fine. Otherwise, it will happen again and again.

Use setTimeout instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!