Javascript - recursive function & setTimeout

I am trying to write a javascript function that, when called, executes the DoSomething () function once, but can be run to execute the function again until it is stopped.

I am using the setTimeout () function. I'm not sure if this is the best method in terms of performance and memory. I would also like to avoid a global variable if possible

<!DOCTYPE html> <html> <script src="jquery.js"></script> <script> var globalCheckInventory = false; $(document).ready(function(){ // start checking inventory globalCheckInventory = true; myTimerFunction(); }); // check inventory at regular intervals, until condition is met in DoSomething function myTimerFunction(){ DoSomething(); if (globalCheckInventory == true) { setTimeout(myTimerFunction, 5000); } } // when condition is met stop checking inventory function DoSomething() { alert("got here 1 "); var condition = 1; var state = 2 ; if (condition == state) { globalCheckInventory = false; } } </script> 
+4
source share
4 answers

This is probably an easier way to do what you are describing:

 $(function () { var myChecker = setInterval(function () { if (breakCondition) { clearInterval(myChecker); } else { doSomething(); } }, 500); }); 
+3
source

Another way to do this is to store the timer id and use setInterval and clearInterval

 var timer = setInterval(DoSomething); function DoSomething() { if (condition) clearInterval(timer); } 
+1
source

I see nothing wrong with your implementation other than contaminating the global namespace. You can use the self-executing function to limit the scope of your variables as follows:

 (function(){ var checkInventory = false, inventoryTimer; function myTimerFunction() { /* ... */ } function doSomething() { /* ... */ } $(document).ready(function(){ checkInventory = true; /* save handle to timer so you can cancel or reset the timer if necessary */ inventoryTimer = setTimeout(myTimerFunction, 5000); }); })(); 
0
source

Encapsulate it:

 function caller(delegate, persist){ delegate(); if(persist){ var timer = setInterval(delegate, 300); return { kill: function(){ clearInterval(timer); } } } } var foo = function(){ console.log('foo'); } var _caller = caller(foo, true); //to stop: _caller.kill() 
0
source

All Articles