How to let a function run after some time?

Asked

Viewed 472 times

1

I have a javascript code ( jquery ) and it performs a function when I move the scroll of the mouse, however, it performs the function several times when I take a whole turn in the scroll. I didn’t want this to happen, wanted him to be able to 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>

Above it takes the Prev and next function of the flexslider, when I turn to one side it runs the Prev, and when I turn to the other it runs the next. But if you spin the ball enough, it runs the Prev or next several times, passing several slides.

1 answer

2


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

I use it a lot with mouse events.

An example would be 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 that:

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);
  • 1

    That’s right!!! It worked!! Thanks Sergio!!!!

  • @Bernardokowacic these functions are very useful. I am glad to have helped.

  • @Sergio, yes, I’m actually doing a horizontal site, and I used the flexslider to display the pages, I just took the automatic scrolling, so I just needed the site to work when I turn the haha mouse scroll.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.