How to call a function only 1 time with mouse scroll?

Asked

Viewed 636 times

2

I need when the user scrolls the mouse up or down, to trigger a specific function only once...

I am using the following code but is not meeting my need:

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 roll the scroll up or down, it calls the function "console log.()" countless times...I need you to call just 1x and call back after 1 second.

** I know or my mistake 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 to occur, but each time I scroll the variable stopScroll will again be false as it will take the global value.

I need help to clear up this logic, and solve my problem. If there’s an easier way to do that, I’d like a suggestion.

2 answers

2

This type of functions / functionality is called debauch. An example could be 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:

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 group of requests: https://jsfiddle.net/1nd8e91k/

-2

Browser other questions tagged

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