The idea and implementation of javascript to prevent scroll events from being executed multiple times

  • 2020-03-26 23:46:24
  • OfStack

This is written primarily to address some common web effects that are expected to differ from the effects of js parsing.

Original code:
 
//The test code
window.onscroll = function(){ 
alert("haha"); 
} 

So it's not convenient to put it inside a script tag and then just slide the mouse over it and think about the prompt box all the time,
And the goal is to only execute one event after the mouse swipe, which is obviously not consistent with the actual effect.

// code improvement - add delay controller.
Since the scroll event is a continuous trigger event, I set up a delayer to execute the function after the user has time to scroll, so the book can be executed only once.
 
//Test code:
function haha(){ 
alert("haha"); 
} 
window.onscroll = function(){ 
setTimeout(haha,500); 
} 

And it turns out that there's a whole bunch of warning boxes that are going to pop up just like that -- so the scroll events are going to line up like a queue, and they're going to be executed in order, so it's not going to work.

This is a good way to conditionally control event execution
 
function haha(){ 
alert("haha"); 
} 
var tur = true; //Create conditions
window.onscroll = function(){ 
if(tur){ setTimeout(haha,500); tur = false; } 
else 
{} 
} 

The good news is that the mouse scrolls to execute the code once, but the problem is that when the mouse scrolls again, the event never executes again.
The reason is that the condition is set to false so that subsequent events are never executed.

The idea is that conditional judgment + delayed execution can solve this problem. At the beginning of the event execution, the variable is resurrected, and the variable is killed after the event execution.
 
var tur = true; 
function haha(){alert("haha"); tur = true; } 

window.onscroll = function(){ 
if(tur){ setTimeout(haha,1000); tur = false; 
}else{ } 
} 

Related articles: