I am using debouncing to execute events after a timeout using settimeout. The problem I have, is that other javascript events expect those events to occur synchronously. Since they are now executing after a timeout, I'd like to be able to trigger them prematurely by other javascript events (so those events requiring them won't fail).
Anywhom, if I do something like:
timeout = setTimeout(function() { alert('hi'); }, 10000);
, and I want that to occur before 10 seconds passes, how can I do that?
The solution can involve jquery if necessary. Thanks!
Edit: Is it possible to do this with just access to the timeout object?
Solution(By Examveda Team) If you call setTimeout() with a time of 0 ms, the function you specify is not invoked right away. Instead, it is placed on a queue to be invoked “as soon as possible” after any currently pending event handlers finish running.
Instead of setTimeout, use run.
You don't actually need to use clearTimeout , you only use it if you wish to cancel the timeout you already set before it happens. It's usually more practical to use clearInterval with setInterval because setInterval usually runs indefinitely.
So, if you make whatever you're delaying its own function:
function sayHi() {
alert('hi');
}
You can use a timeout and a regular function call:
var timeout = setTimeout(sayHi, 10000); // say hi after 10 seconds
Or to call it before the timeout expires, just call the function whenever you need to:
sayHi();
Am I on the right track here? If you need to cancel the timeout, call clearTimeout()
on your timeout
variable.
if (timeout)
clearTimeout(timeout);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With