How to call a function only once with mouse scroll?

2

I need when the user rolls the mouse scroll up or down, a specific function is triggered only once ...

I'm using the following code but it does not meet my needs:

var stopScroll = false;

$(window).scroll(function (event) {   

var scrollAtual = $(this).scrollTop();

if (scrollAtual > lastScrollTop) {      
    // down scroll code     
    if(stopScroll == false){
        console.log('scroll para baixo'); 
        stopScroll = true;

        //depois de 1 segundo ativa a função do scroll down novamente
        setTimeout(function(){              
            stopScroll = false;
        }, 1100);   
    }       
} else {    
    // up scroll code        
    if(stopScroll == false){
        console.log('scroll para cima'); 
        stopScroll = true;

        //depois de 1 segundo ativa a função do scroll up novamente
        setTimeout(function(){              
            stopScroll = false;
        }, 1100);   
    }
}             
lastScrollTop = scrollAtual;         

});

When I scroll up or down, it calls the function " console.log () " countless times ... I need to call only 1x and call again after 1 second.

** I know or my error more or less, at the beginning of the code I declare the variable stopScroll as false, and within the " $ (window) .scroll (function (event ) "I change its value to true for a stop, but each time I scroll the variable stopScroll will return false because it will take the global value. >

I need help to sort this logic out, and solve my problem. If there is an easier way to do this, I'd like a suggestion.

    
asked by anonymous 20.05.2016 / 21:32

2 answers

2

This kind of functions / functionality is called debounce . An example could look like this:

function debounce(fn, delay) {
    var block, self = this;
    return function() {
        if (block) return;
        block = true;
        block = setTimeout(function() {
            block = false;
        });
        fn.apply(this, arguments);
    }
}

and then to use would be:

var superFuncao = debounce(1000, function(event){
    // o resto da tua função aqui
});

$(window).scroll(superFuncao);

Take a look at this example and notice how it runs the function only once per request group: link

    
20.05.2016 / 22:36
-2

About debounce and throttle in JavaScript, I recommend this lib:

jquery-throttle-debounce

    
27.11.2017 / 18:41