Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have "setInterval" set too fast?

I have a setinterval function in my javascript that I want to be as fast as possible, i.e. check the status of an event every 1ms. Is it possible that this would be asking too much from a user's browser? It seems to work just fine, but I am wondering if its a bad practice.

like image 945
Rafie Avatar asked Dec 08 '22 20:12

Rafie


1 Answers

It is not only possible, it's quite common. It's a race-condition by its very nature. If you depend on the code inside the callback to be executed before the next interval, use a recursive setTimeout instead.

Also, unless your interval is called lockUpBrowser, that duration between callbacks is likely much too short for realistic performance handling.

(function myRecursiveTask() {
    // Do your task here
    myTask();

    if (!someConditionToAllowABailOut) {
        setTimeout(myRecursiveTask, 100); // 100ms loop
    }
}());
like image 86
AlienWebguy Avatar answered Jan 02 '23 08:01

AlienWebguy