Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop/override a Jquery TimeOut function?

I have a small jquery snippet that displays notification message at the top of the screen in response to user actions on a page. The notification is often displayed after Ajax actions with dynamic content inside it.

For example:

$("#mini-txt").html("Thank you!"); $("#mini").fadeIn("fast"); setTimeout(function() {$("#mini").animate({height: "hide", opacity: "hide"}, "medium");}, 3000); 

The notification works well, except when a user does two or more actions in rapid succession, in which case the TimeOut function will confuse itself and the second message appears to come inside the previous 3000 milliseconds.

Is there a way to "kill" the previous notification if a new action is performed. I've got no problem with the actions/selectors, just the TimeOut function.... either stopping it or overriding it somehow. Or perhaps there's a better alternative for getting the message to linger on the screen for a few seconds before disappearing?

Thank you.

like image 714
Tom Avatar asked Apr 05 '10 13:04

Tom


People also ask

How do I stop timeout?

To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.

What is the alternative for setTimeout in JavaScript?

The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.

What is jquery setTimeout?

The setTimeout() function of JavaScript is used to delay certain action or execution of the code placed directly inside that function or at another JS function. The delay or time is specified in milliseconds in setTimeout function.

Why is setTimeout executed at last?

setTimeout schedules the function for execution. That scheduler doesn't do its thing until after the current thread yields control back to the browser, e.g. after the last logging statement has executed.


2 Answers

First, you store the return value for the setTimeout function:

// Set the timeout var timeout = setTimeout(function()     {         // Your function here     }, 2000); 

Then, when you're ready to kill the timeout...you just call clearTimeout with the stored value from the previous call to setTimeout.

// Then clearn the timeout clearTimeout(timeout); 
like image 73
Justin Niessner Avatar answered Sep 20 '22 15:09

Justin Niessner


You can use .stop()

Stop the currently-running animation on the matched elements.

like image 42
rahul Avatar answered Sep 24 '22 15:09

rahul