Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
133 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...