Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do nothing if the same function is already running

Tags:

javascript

I have a javascript function that runs every 3 seconds, is there any way to do nothing if a previous instance of the function is already running?

like image 503
Boos93 Avatar asked Sep 05 '25 22:09

Boos93


1 Answers

I assume you are running heavy function with setInterval and want to skip one tick if previous one has not completed.

Then, instead of

function yourfoo() {
   // code
}

setInterval(yourfoo, 3000);

do:

function yourfoo() {
   // code
   setTimeout(yourfoo, 3000);
}

setTimeout(yourfoo, 3000);

This guarantees next call is not scheduled until previous one is completed.

like image 104
Krizz Avatar answered Sep 08 '25 14:09

Krizz