我正在尝试构建一个通知系统,我从UI / UX开始,我开始构建一个概念证明,但我正在努力调试我的超时。任何帮助都会很棒。
JavaScript的:
//Remove notification after 5 seconds
var timer;
new function(){
timer = setTimeout(function(){
removeNotification($notification);
}, 5000);
}
//If any notification is hovered then start the timer again
jQuery("#notificationList").hover(function (){
clearTimeout(timer);
});
答案 0 :(得分:0)
new Function() {..}
- >以这种方式声明函数会导致函数无法编译,并且可能比声明函数的其他方式更慢。
所以,有一个IIFE,如下所示。
//Remove notification after 5 seconds
var timer = false;
(function(){
timer = setTimeout(function(){
removeNotification($notification);
}, 5000);
}());
并改变:
//If any notification is hovered then start the timer again
jQuery("#notificationList").hover(function (){
clearTimeout(timer);
});
要:
//If any notification is hovered then start the timer again
jQuery("#notificationList").hover(function () {
removeNotification($notification);
timer && clearTimeout(timer);
});
如果最初未设置定时器,clearTimeout
将无法运行。希望有所帮助。
你的整个代码(因为我无法分叉你的笔):
//Notification markup
var notificationMarkup = '<li class="notification"><a href="#"><span class="image-wrapper"><img src="http://www.guestsofdave.com/images/scarlett%20johansson.jpg"/></span><span class="message-wrapper"><span class="message"><span class="info"><strong>Scarlett</strong> has replied to your <strong>forum post</strong>.</span><span class="meta"><i class="application forum"></i> <span class="notification-date">1 Hour Ago</span></span></span></span></a><span class="close-db-notification"></span></li>';
//CSS animation end hook
var animationEnd = "webkitAnimationEnd oanimationend msAnimationEnd animationend";
//Remove notification function
function removeNotification($notification) {
$notification.addClass("animated zoomOut");
$notification.animate({
height: 0
}, 150, function() {
$notification.remove();
});
}
//New notification
jQuery(".new-notification").click(function() {
//Gets the last notification added
var $notification = jQuery("#notificationList .notification").last();
//Append the notification markup into the list
jQuery("#notificationList").append(notificationMarkup);
//Animate the notifications height from 0 to 90px and then animate it in
$notification.animate({
height: 90
}, 150, function() {
jQuery(this).css('visibility', 'visible');
jQuery(this).addClass("animated zoomIn");
});
//Remove animation classes when animation ends
$notification.on(animationEnd, function() {
jQuery(this).removeClass("animated zoomIn")
});
//Remove notification after 5 seconds
var timer = false;
(function() {
timer = setTimeout(function() {
removeNotification($notification);
}, 5000);
}());
//If any notification is hovered then start the timer again
jQuery("#notificationList").hover(function() {
removeNotification($notification);
timer && clearTimeout(timer);
});
});
//Remove notification on click
jQuery(document).on("click", ".close-db-notification", function() {
var $notification = jQuery(this).closest(".notification");
removeNotification($notification);
});