Skip to content
Advertisement

setTimeout runs only once then not working

I got JS as below. I want all bootstrap alerts to dissaper after 1 sec. It works just one time but when i add more alerts they stays as they are. What is the cause of that?

$(document).ready(function () {
function flashh(message, category) {
    if (category == "error") {
      var icon = "icon-exclamation-sign";
      category = "danger";
    } else if (category == "success") var icon = "icon-ok-sign";
    else var icon = "icon-info-sign";
    $(
      '<div class="alert alert-' +
        category +
        '"><i class="' +
        icon +
        '"></i>&nbsp;<a class="close" data-dismiss="alert">×</a>' +
        message +
        "</div>"
    ).prependTo("#putFlashMsg");
  }
});

setTimeout:

$(document).ready(function () {
  window.setTimeout(function () {
    $(".alert")
      .fadeTo(1000, 0)
      .slideUp(1000, function () {
        $(this).remove();
      });
  }, 5000);
});

Advertisement

Answer

That’s because setTimeout is only called once. If you want to have multiple calls, use setInterval, that is used exactly the same way but is called until clearInterval stops it.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement