Home > Web Front-end > JS Tutorial > body text

The idea and implementation of javascript preventing scroll event from being executed multiple times_javascript skills

WBOY
Release: 2016-05-16 17:16:46
Original
1078 people have browsed it

This is mainly written to solve the problem that some common web page special effects have different expectations and effects during js parsing.

Original code:

Copy code The code is as follows:

//Test Code
window.onscroll = function(){
alert("haha");
}

You can install it in the script tag and keep thinking about the prompt box after sliding the mouse. So it is very inconvenient,
and the purpose is to only execute the event once after the mouse slides. This effect is obviously inconsistent with the actual situation.

//Code improvement--add delayer.
Since the scroll event is a continuous trigger event, then I set up a delayer to execute the function after the user slides the mouse. Can't it be executed only once?
Copy code The code is as follows:

//Test code:
function haha() {
alert("haha");
}
window.onscroll = function(){
setTimeout(haha,500);
}

result I found that a lot of warning boxes still pop up like the above - it can be seen that the scroll events are lined up in a line like a queue and executed in order, so this way is blocked, so I have to find another way.

Controlling event execution through conditions is a good method
Copy the code The code is as follows:

function haha(){
alert("haha");
}
var tur = true; //Create condition
window.onscroll = function(){
if(tur){ setTimeout(haha,500); tur = false; }
else
{}
}

Fortunately, the code is executed once when the mouse scrolls, the problem When the mouse is scrolled again, the event is no longer executed.
The reason is that the condition is set to false so subsequent events will never be executed.

The idea is that conditional judgment and delayed execution can solve this problem. At the beginning of event execution, the variable is resurrected and after the event is completed, the variable is killed.
Copy code The code is as follows:

var tur = true;
function haha() {alert("haha"); tur = true; }

window.onscroll = function(){
if(tur){ setTimeout(haha,1000); tur = false;
} else{ }
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template