2015-04-06 80 views
0

我试图用JS做'烤面包机'通知系统,但它无法按预期运行。嵌套setTimeouts运行一次

无论何时有与用户相关的nodeJS或AJAX的更新,我想显示一个可能嵌套的通知框,如果同时存在多个通知,有点像facebook,并在5秒后被移除,独立于此刻正在运行的其他通知。

但是只有最后一个通知会消失并被删除,其余的旧通知将保持可见....我无法找到造成这种情况的原因。

这是我在mielikki对象内的代码。

var mielikki = { 
    notifHooks: [], 
    toaster : { 
    notifCount : 0, 
    launch : function(ops) { 
     message = ''; 
     delay = 5000; 
     msgType = 'generic'; 
     if("message" in ops) { 
      message = ops.message; 
     } 
     if("delay" in ops) { 
      delay = ops.delay; 
     } 
     if("msgType" in ops) { 
      msgType = ops.msgType; 
     } 
     this.notifCount += 1; 
     $('#toaster_template').clone().attr('id','notification-'+this.notifCount).html(message).appendTo('#notifications'); 
     var target = $("#notification-"+this.notifCount); 
     var test = setTimeout(function() { target.fadeOut("slow",function() { target.remove(); })},5000); 
     mielikki.notifHooks.push(test); 
    } 
} 
} 

div toaster_template是保留每个新通知克隆的基本div。

从任何来源或控制台会做这样的事:

mielikki.toaster.launch({'message' : 'test'}); 

但同样,如果前面是同时运行2+时间只有最后/最新通知将如预期做。

+0

你看着约翰爸爸的Toastr库?这很简单,效果很好。 http://www.johnpapa.net/toastr100beta/ – Delorian 2015-04-06 01:02:13

+0

从来没有听说过尝试和现在测试它,迄今为止这么好,谢谢!就是我正在尝试的! - 然而,为什么我的代码不能工作令人失望,我正在杀死它。 – 2015-04-06 05:33:23

回答

0

我没有看到任何错误,也许超时被取消在其他地方(与notifHooks阵列),我认为这是一个范围问题,但没有办法排队两个超时与共享元素与您发布的功能,不回答你的问题,但我做了这个测试只是为了确认,你做了什么,有什么不妥:

function notification(message) { 
 
    var notification = $('<div />').html(message); 
 
    $(document.body).append(notification); 
 
    
 
    setTimeout(function() { 
 
    notification.fadeOut(500, function() { notification.remove() }); 
 
    }, 1000); 
 
} 
 

 
notification('hello'); 
 
notification('world'); 
 

 
setTimeout(function() { 
 
    notification('1000ms'); 
 
}, 1000); 
 

 
setTimeout(function() { 
 
    notification('1500ms'); 
 
}, 1500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

事实上 - 以多种方式测试它,它不起作用:(为什么它不起作用没有意义。 – 2015-04-06 05:34:25