How to let a function run after a while?

1

I have a code in javascript (jquery) and it performs a function when I move the scroll of the mouse, however, it executes the function several times when I go around the scroll. He did not want this to happen, he wished he could only run again after a while. Does anyone know how I could do this?

$(window).bind('mousewheel', function (event) {
    if (event.originalEvent.wheelDelta >= 0) {
        $('.flexhome').flexslider('prev');
        console.log('passa_slide');
        return false;
    } else {
        $('.flexhome').flexslider('next');
        console.log('volta_slide');
        return false;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Up it picks up the prev and next function from the flexslider, when I spin to one side it performs the prev, and when I spin to the other it performs the next. However if you spin the ball a lot, it executes the prev or next several times, passing several slides.

    
asked by anonymous 30.12.2015 / 19:25

1 answer

2

You need a function that debounce, ie: avoid being called until a certain time has passed since the last call.

I use this a lot with mouse events.

An example would look like this:

function debounce(fn, delay) {
  var timer = null;
  return function () {
    var context = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };
}

and then you can use / call it like this:

var funcaoMagica = debounce(function (event) {
    if (event.originalEvent.wheelDelta >= 0) {
        $('.flexhome').flexslider('prev');
        console.log('passa_slide');
        return false;
    } else {
        $('.flexhome').flexslider('next');
        console.log('volta_slide');
        return false;
    }
}, 250);
$(window).bind('mousewheel', funcaoMagica);
    
30.12.2015 / 19:29