Search code examples
javascripttimeout

force a javascript timeout function to execute immediately


If I have set a timeout in javascript

var myTimeoutId = setTimeout( function(){
    ... do some stuff ....
}, 15000);

and a different event makes me need to have that timeout execute immediate, is there a way that I can use that stored id to execute the function? I know that I could store off a reference to that function, call clearTimeout on myTimeoutId and then call the function directly, but there's a decent amount of book keeping involved in that.

Is there a function along the lines of executeNow( myTimeoutId ) ?


Solution

  • No. You need to create the function separately so it can be called from anywhere:

    function fn (){
        // ... do some stuff ....
    }
    
    var myTimeoutId = setTimeout( fn, 15000);
    
    // one possibility
    function other () {
        clearTimeout(myTimeoutId);
        fn();
    }