Javascript 如何停止/覆盖 Jquery TimeOut 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2578628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to stop/override a Jquery TimeOut function?
提问by Tom
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.
我有一个小的 jquery 片段,它在屏幕顶部显示通知消息以响应用户在页面上的操作。通知通常在包含动态内容的 Ajax 操作之后显示。
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.
通知效果很好,除非用户快速连续执行两个或多个操作,在这种情况下 TimeOut 函数会混淆自身并且第二条消息似乎出现在前 3000 毫秒内。
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?
如果执行新操作,是否有办法“杀死”先前的通知。我对动作/选择器没有任何问题,只是 TimeOut 功能......要么停止它,要么以某种方式覆盖它。或者也许有更好的选择让消息在消失之前在屏幕上停留几秒钟?
Thank you.
谢谢你。
回答by Justin Niessner
First, you store the return value for the setTimeoutfunction:
首先,存储setTimeout函数的返回值:
// Set the timeout
var timeout = setTimeout(function()
{
// Your function here
}, 2000);
Then, when you're ready to kill the timeout...you just call clearTimeoutwith the stored value from the previous call to setTimeout.
然后,当您准备好终止超时时……您只需clearTimeout使用上次调用的存储值调用setTimeout.
// Then clearn the timeout
clearTimeout(timeout);
回答by rahul
回答by PetersenDidIt
jQuery 1.4 has a built in method to handle delays for animations you can do something like this:
jQuery 1.4 有一个内置的方法来处理动画的延迟,你可以这样做:
$("#mini-txt").html("Thank you!");
$("#mini").fadeIn("fast").delay(3000).animate({height: "hide", opacity: "hide"}, "medium");
And then later when you want to clean the animation queue you can do:
然后当你想清理动画队列时,你可以这样做:
$("#mini").stop(true);
回答by Tadeusz Majkowski
This will clear timeout after function run with delay 500ms
这将在函数运行延迟 500 毫秒后清除超时
var timeout = setTimeout(function(){
/* YOUR FUNCTION */
}, 500, function(){
clearTimeout(timeout);
});

