6

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

2 Answers 2

8

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

in nodejs:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.