N
N
nfobdw1432015-08-17 13:23:52
NVIDIA
nfobdw143, 2015-08-17 13:23:52

How to execute a function on completion of a frequently repeated event, and not many times in a row?

There is such a code. Everything works fine, but when scrolling more than one scroll, owl.next(); and owl.prev(); fire repeatedly, and as a result, all slides are scrolled to the end / beginning, respectively. How to make it always scroll to one slide, no matter how much the user "spun" the mouse wheel?

$(document).ready(function() {
   
    var owl = $(".sldr").owlCarousel().data('owlCarousel');

    $(window).on('mousewheel', function(event) {
        
        if(event.deltaY < 0){
            owl.next();           
        }
        if(event.deltaY > 0){
            owl.prev();           
        }
    });  
     
});

Tried to set false/true on beforeMove: afterMove: and start scrolling only on true, but afterMove is executed before the slide is scrolled.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2015-08-17
@nfobdw143

The fact is that during the rotation of the mouse wheel, the mousewheel event fires many times. Accordingly, the event handler fires the same number of times.
To avoid this, you need to debounce the handler, that is, make it run once n milliseconds after its last call. If n milliseconds have not passed since the last call , and the handler was called again, its execution is delayed by another n milliseconds.
In this case, the handler will be executed 100 milliseconds after the scroll events stop coming (100 is just an example, the real value should be selected based on the situation):

$(document).ready(function () {
    var owl = $(".sldr").owlCarousel().data('owlCarousel');

    $(window).on('mousewheel', debounce(function (event) {
        var direction = event.originalEvent.deltaY < 0 ? 'next' : 'prev';
        owl[direction]();
    }, 100));   
});
debounce function code
function debounce(func, wait, immediate) {
    var timeout, args, context, timestamp, result;

    var later = function () {
        var last = new Date().getTime() - timestamp;

        if (last < wait && last >= 0) {
            timeout = setTimeout(later, wait - last);
        } else {
            timeout = null;
            if (!immediate) {
                result = func.apply(context, args);
                if (!timeout) context = args = null;
            }
        }
    };

    return function () {
        context = this;
        args = arguments;
        timestamp = new Date().getTime();
        var callNow = immediate && !timeout;
        if (!timeout) timeout = setTimeout(later, wait);
        if (callNow) {
            result = func.apply(context, args);
            context = args = null;
        }

        return result;
    };
}

Interactive Example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question