Why do we need throttling and anti-shaking
When an event is triggered frequently, the event handler will be executed frequently. If the handler performs some time-consuming and performance-consuming operations, the page will be jammed or even the browser will crash. In this case, throttling and shaking prevention are required
What is throttling and anti – shaking
- The throttle
The event handler executes once in a while when event frequency is triggered
- Image stabilization
If an event that fires frequently does not fire again within a specified time, the event handler executes, and if the event fires again within that time, the timer restarts
When are throttling and shaking prevention necessary
- scroll
- resize
- Form input event validation
- .
implementation
-
Image stabilization
<html lang = "en">
<style>
#wrap .scrollBox.#wrap .list{
float: left;
}
.scrollBox {
width: 40%;
height: 500px;
margin-right: 5%;
border: 1px solid red;
overflow: scroll;
}
.list {
width: 40%;
border: 1px solid red;
}
</style>
<body>
<div id = "wrap">
<div class = "scrollBox"><! Dynamic content generation --></div>
<ul class = "list">
<li>I am a list</li>
</ul>
</div>
</body>
<script>
// The function can be used to prevent trembling
function debounce (handle, delay) {
let timer = null
return function () {
if (timer) {
// console.log('clearTimeout, clear timer')
clearTimeout(timer)
}
// console.log('setTimeout, set timer')
timer = setTimeout(handle, delay)
}
}
// Event handler that generates a LI node and adds it to the end of the UL node
function handle () {
const node = document.createElement('li')
const text = document.createTextNode(Date.now())
node.appendChild(text)
document.getElementsByClassName('list') [0].appendChild(node)
}
// Add event listeners to form a closure
document.getElementsByClassName('scrollBox') [0].addEventListener('scroll', debounce(handle, 500))
// Generate the contents of the scroll bar. The following sections and the HTML and CSS above are only for constructing an experimental environment
let content = ' '
for (let i = 0; i < 1000; i++) {
content += 'Scroll over me.'
}
const textNode = document.createTextNode(content)
document.getElementsByClassName('scrollBox') [0].appendChild(textNode)
</script>
</html>
Copy the code
debounce
Why does the function have an anti-shake function?
Document. The getElementsByClassName (‘ scrollBox) [0]. AddEventListener (‘ scroll ‘debounce (handle, 500)), the line of code that formed a closure, The debounce function returns a function that has been executing for the duration of the Scroll event (to test the uncommented two lines of console.log()), such as: The first time you scroll, the first time you execute the function returned by debounce, discover!! If (timer === false) {if (timer === false) {if (timer === false) Execute clearTimeout to clear timer, but then you will find that the timer task is cleared before it is executed, which meets the requirements of anti-shake. Keep scrolling and repeat the above process (the function is still executing) until you stop scrolling, and the previous timer task will not be cleared. When the specified delay time expires, handle is executed, the next scroll is started, the last timer is cleared, and the process is repeated
-
The throttle
With the basis of anti – shake, throttling here, will omit the HTML code to build the experimental environment, directly on the implementation of throttling method, there are two ways to achieve, respectively, is time stamp and scheduled task
Timing task
// throttling function
function throttle (handle, delay) {
// The key point of throttling is the timer. After the timer is assigned, the timer will be reset to NULL only after the scheduled task is executed
let timer = null
return function () {
if(! timer) {/ / set the timer
timer = setTimeout((a)= > {
handle()
// After the scheduled task is complete, the timer is disabled
timer = null
}, delay)
}
}
}
// Event handlers
function handle () {
console.log('I am handle function')}// Add event listeners
document.getElementById('app').addEventListener('scroll', throttle(handle, 1000))
Copy the code
The time stamp
// throttling function
function throttle (handle, delay) {
// The key to throttling
let prevTime = Date.now()
return function () {
if (Date.now() - prevTime >= delay) {
// Execute the event handler when the time is up and reset prevTime
handle()
prevTime = Date.now()
}
}
}
// Event handlers
function handle () {
console.log('I am handle function')}// Add event listeners
document.getElementById('app').addEventListener('scroll', throttle(handle, 1000))
Copy the code
What’s the difference between throttling and anti-shaking
- In common
Both limit the frequency of execution of event handlers
- The difference between
Throttling: Event handlers are executed periodically and repeatedly, no matter how often the event is triggered. Stabilization: Handlers are executed only when the event is last triggered (not again within a specified time)
Application scenarios
-
Image stabilization
- Search The search box and form input validation are triggered
input
Operation of events
The final event handler (e.g., searching for content, validating form content) is executed only after the content is entered
- Window resize event
After the window resize stops, the event handler is executed one last time
-
The throttle
- The scene with frequent mouse clicks
Games like Whack-a-Mole, CS, League of Legends, Honor of Kings, etc., require frequent click-action scenarios
- The drop-down refresh
Pull down to load more, all the way down, but only execute the event handler once within an event (load content)