Search code examples
javascriptjquerytoastr

Show Notification after certain Duration - toastr.js


I have a list of Messages I need to show to the User, which are loaded using Ajax after certain periods of time in data.NotificationDtos

The thing is that I have to show one Message at a time for a certain amount of time say 10 seconds,

At the moment it is displaying all notifications at once.

So I need my steps to be:

  1. After Ajax Request toastr first Message with toastr.info(val.DetailedMessage, val.EventMessage);

  2. Then Show Above Toastr Message for certain time.

  3. Then continue with other Messages until all are complete.

But I come around how to do that.

function loadNotifications() {
        $.ajax({
            url: '@Url.Action("GetNotifications", "Users")',
            dataType: "json",
            success: function (data) {                   
                $.each(data.NotificationDtos, function (i, val) {
                    toastr.info(val.DetailedMessage, val.EventMessage);
                });

            }
        });
    }

Solution

  • A rudimentary implementation could use window.setTimeout:

    var messages = ["Hello", "World", "Including", "Antartica"]; 
    
    function showMessages(messages, interval){
        // Loop through messages
        for(var i = 0; i < messages.length; i++){
            // Create timer for each message
            window.setTimeout((function(){
                var message = messages[i];
                return function(){
                    toastr.info(message);
                }
            })(), i*interval*1000);
        }
    }
    
    // Show the list of messages, separate them by 3 seconds apiece
    showMessages(messages, 3);
    

    Proof of concept: JSFiddle.