0

I'm trying to skip a delay event in JavaScript. Say( If I mouse wheel for 4 times continuously the first one ill get fired followed by the second, third and fourth one. In my scenario if the first event fired and when the second/third/fourth events are in delay or slow I want to speak the second and third event getting fired and must directly fire the final event (say fourth event))

Is this possible using JS/Jquery! And can anyone suggest me some sample for it if possible!

Sorry if I don’t make much sense, I am a beginner here.

1 Answers1

0

It sounds like you're describing a debounce function, which will fire on the first event but merge subsequent events within a defined timeframe.

This plugin should achieve what you're looking for: http://benalman.com/projects/jquery-throttle-debounce-plugin/

This question and answer may also be helpful.

Based on the autocomplete example on this page, http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/, the final (4th in your example) event should be fired, but any intermediate events that happen in quick succession will be skipped.

Here is a Stackblitz example, debouncing a mousewheel event to every 0.1s. You simply need to include the plugin and then do:

$(document).ready(function () {
    $('body').bind('mousewheel', $.debounce(100, debounceEvent));
    function debounceEvent(event) {
        // Process mouse wheel event here
        console.log(event);
    }
});

If you do a quick scroll, only the last event should be emitted.

Matt Saunders
  • 3,538
  • 2
  • 22
  • 30
  • Yes! @Matt Saunders. I can ignore the event but how can I call the final event which is triggered! –  Apr 07 '20 at 07:29
  • I think the final emission should work, if you give it a try. If you look at the 'pretend autocomplete' option on here: http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/ The final text input is displayed, it just skips any events that happen in quick succession between the first and last event. – Matt Saunders Apr 07 '20 at 07:32
  • Have added an example @NoobDeveloper - let me know how you get on. – Matt Saunders Apr 07 '20 at 12:17