Search code examples
javascriptdelaysettimeoutexecution

Store setTimeout and call it later


Look at the following code:

var timer=setTimeout(function(){increase();}, 8);

This setTimeout function will be executed immediately, but I want it to execute later. Why?

Example:

function increase(i)
                 {
                  i++; if(i==100) return;
                  var timer=setTimeout(function(){increase(i);}, 8);
                  }

Now, I need to stop and exit this function within another function when certain thing happen:

if (a==b) clearTimeout(timer);

The thing that bothers me is that variable timer is getting assigned, whenever function increase runs, but it does not need to, and I believe it is bad practice. That is why I need to assign to it only once, before function run and execute it later when need arrives.

I hope you understood, and btw, those are just examples, not my code.


Solution

  • If you want the operation of one function to change the conditions of another, just declare a boolean variable within the scope of both functions and change it's value depending on a terminator function.

    For example, take a look at this code:

    var exit = false;
    
    function increase(i) {
        if(i==100 || exit) return;
        setTimeout(function(){ increase(++i) }, 1000);
    }
    
    function terminator(a, b){
        exit = (a==b);
    }
    
    increase(0);
    

    Here, if terminator is ever called with a pair of equal arguments like:

    setTimeout(function(){ terminator(true, 1) }, 5000) // timeout of 5 seconds means increase will run 5 times
    

    the recursive call of setTimeout within the increase function will not be reached (after 5 seconds), as the function will return before reaching that line of code.

    If terminator is never called, or called with unequal arguments like:

    setTimeout(function(){ terminator(true, false) }, 5000) // using setTimeout here is just arbitrary, for consistency's sake
    

    increase will only time out once it's completed 100 recursions (in other words, after 100 seconds have elapsed)

    Hope this helps!