简体   繁体   中英

Stop current Javascript event

I have this simple to-do-list with JQuery. When I delete or add an item, there will be a message shown with fadein, fadeout and delay JQuery method.

The whole app works well except that when I have many items which I want to delete many items very quickly, the message will still continue to show one by one.

I try e.stopPropagation() to stop the previous event but it seems like not working.

function clearMesg() {            
     $(".mesg").stop().fadeIn(500).delay(500).fadeOut(500);
}

$(".del").on("click", function (e) {
      e.stopPropagation();

      $(this).parent().remove();

      $('.mesg').text("Deleted.");
      clearMesg();

});

You don't need to stop the previous event; in JavaScript, events are queued up and run one after the other, so the last event handler will have finished before the current one is run. The animation that you're running with jQuery, on the other hand, runs asynchronously, so other event handlers will run while the animation is in progress, causing it to restart.

You could check whether an animation is already running before starting another one using jQuery's :animated selector (see "How do I find out with jQuery if an element is being animated?" ):

function clearMesg() {
     let $mesg = $(".mesg");
     if (!$mesg.is(":animated")) {
          $(".mesg").stop().fadeIn(500).delay(500).fadeOut(500);
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM