我在我的js代码的一部分中收到了一些奇怪的行为。点击删除setTimeout
我有一些通知出现在页面顶部的栏中,然后在一段时间后消失。我用一个简单的setTimeout()
来实现这个目标。
有时,当页面加载时,通知将显示为特定url查询字符串的结果,但当用户单击按钮时需要显示新字符串。我希望旧的消失,并出现新的。我正在使用变量来保留对setTimeout()
的引用以取消它。但是,当我尝试这样做时,我设法创建了一个循环,最终导致我的chrome选项卡崩溃。
我已经把我的说明问题的jsfiddle - 而另一个是可见的会崩溃的浏览器选项卡http://jsfiddle.net/5Nm4c/
点击show notification
。如果在没有显示任何内容的时候点击它,那很好。
这里是我的JS:
var Notification = {
// close main notification bar
close: function (callback) {
$('#notification-bar').fadeOut(250, function() {
// reset its position and fade it back in so it is ready to go again
$(this).css('top', -100).fadeIn(1);
// check if a callback function has been passed in
if (typeof callback === 'function') {
callback();
}
});
},
// open notification bar with the appropriate css class and message
open: function (message) {
// if the notification bar is already visisble
if (verge.inViewport($('#notification-bar'))) {
// hide and then show it with the new message
window.clearTimeout(Notification.timeout);
Notification.close(Notification.open(message));
return false;
}
$('#notification-bar').html(message);
$('#notification-bar').animate({
'top': 0
}, 250, function() {
Notification.timeout = window.setTimeout(function() { Notification.close() }, 1500);
});
},
timeout: null
}
Notification.open('hello');
$('#button').click(function(e){
e.preventDefault();
Notification.open('link clicked');
});
我用https://github.com/ryanve/verge/,因为它有一些很好的方法来检查是否元素在视口中可见。
有人能告诉我我的错误在哪里吗?