BostonJohn
BostonJohn

Reputation: 2661

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 ) ?

Upvotes: 6

Views: 6220

Answers (2)

MohammedElmsellem
MohammedElmsellem

Reputation: 31

in nodejs:

const timeout = setTimeout(() => {
  console.log("timeout function");
}, 10000);

// execute timeout function
timeout._onTimeout();
clearTimeout(timeout);

Upvotes: 1

user2625787
user2625787

Reputation:

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();
}

Upvotes: 8

Related Questions