0

I have an event called customevent. When this event occurs I need to toggle a class on a div.

This is working however the event sometimes fires multiple times in quick succession. When this happens the class is added and removed again which is not what I want.

  $(document).on('customevent', function(event, data) {
        $('.class').toggleClass('toggle-class');
  });

When the event occurs I need the class to be immediately toggled. However I need the class to not be able to be toggled for 1 second even if the event continues to fire. The following is not working.

  var is_blocked;

  $(document).on('customevent', function(event, data) {
      if (is_blocked !== true) {
        $('.class').toggleClass('toggle-class');
        is_blocked = true;
        setTimeout(function(){
          is_blocked = false; 
        }, 1000);
      }
  });
Evanss
  • 23,390
  • 94
  • 282
  • 505
  • 2
    Possible duplicate of [disable click event handler for a duration of time](http://stackoverflow.com/questions/8335177/disable-click-event-handler-for-a-duration-of-time) – JNF Nov 10 '15 at 09:28

3 Answers3

1

Why not set is_blocked to a timestamp rather than a boolean? Something like:

var blocked_time = 0;

$(document).on('customevent', function(event, data) {
    if (blocked_time + 1000 < new Date().getTime()) {
        $('.class').toggleClass('toggle-class');
        blocked_time = new Date().getTime();
    }
});
Oliver
  • 11,297
  • 18
  • 71
  • 121
0

You are very close, but no sigar

var is_blocked = false;

$(document).on('customevent', function(event, data) {
    if (!is_blocked) {

        $('.class').toggleClass('toggle-class');

        is_blocked = true;

        setTimeout(function(){
            is_blocked = false; 
        }, 1000);
    }

    is_blocked = true; 
    //I'll be set to true, and in a second ill be false
    //thanks to the timeout. This might not be a stable solution
    //because what happens if the function is spammed for over a second?
});

You need to set is_blocked to true every time the function runs independent of the if-statement.

NachoDawg
  • 1,533
  • 11
  • 21
0

You might want to look at the debounce (or throttle in lodash) function, which might be used like this

var throttled = debounce(function() {
  // your actions will be executed at max
  // once every 1000ms
}, 1000);

$(document).on('event', throttled);

On the subject: https://davidwalsh.name/javascript-debounce-function

Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106