Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute settimeout early

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?

like image 747
GoldenNewby Avatar asked Feb 24 '12 04:02

GoldenNewby


People also ask

What will happen if we call setTimeout () with a time of 0 ms?

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.

What can I use instead of setTimeout?

Instead of setTimeout, use run.

What happens if you don't clear setTimeout?

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.


1 Answers

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);
like image 85
Cᴏʀʏ Avatar answered Sep 21 '22 10:09

Cᴏʀʏ