- In front-end development, when processing events such as Scroll resize input Mousemove, it is usually not desired that the event handler is triggered continuously. Shaking and throttling can better solve this problem.
- To illustrate the phenomenon of continuously firing events
<! -- HTML code -->
<body>
<input style="width: 100%; outline: none;" type="text">
<div style="display: flex;">
<div class="showThis" style="height: 100px; background: #eee; flex: 1;"></div>
<div class="showEvent" style="height: 100px; background: rgb(179, 155, 155); flex: 1;"></div>
</div>
<script>
let input = document.querySelector('input');
let showThis = document.querySelector('.showThis')
let showEvent = document.querySelector('.showEvent')
input.oninput = valueChange
function valueChange(e) {
showThis.innerHTML = this.value
showEvent.innerHTML = e.target.value
}
</script>
</body>
Copy the code
The effect is as follows:
If more complex code, such as An Ajax request, is executed in the handler, there is a performance cost
Image stabilization (debounce)
- The so-called anti-shaking means that the handler function of the event is executed only after the event is triggered in unit time. If the event is triggered again in unit time, it will be timed again to ensure that the code in the event is executed only once in unit time
// Anti-shaking function
function debounce(func, wait) {
let timer = null
return function () {
const that = this
const args = [...arguments]
if (timer) clearTimeout(timer)
timer = setTimeout(func.bind(this. args), wait) } }// Set the event handler to the shaking function
input.oninput = debounce(valueChange, 500)
Copy the code
Effect:
The effect of the stabilization is that only the last fired function is executed
The throttle (throttle)
- When an event is fired, the code in the event can be executed at most once per unit of time, so throttling reduces the number of times the code is executed per unit of time, thus improving performance.
// Throttling function
function throttle(func, wait) {
let timer = null
return function () {
const that = this
const args = [...arguments]
if (timer) return
timer = setTimeout(() = > {
timer = null
func.apply(that, args)
}, wait)
}
}
// Use the throttling function to handle the event
input.oninput = throttle(valueChange, 500)
Copy the code
Effect:
The effect of throttling is that the function is executed every unit of time
conclusion
- Both shaking and throttling are designed to address the performance cost of frequently triggering an event.
- Shaking is performed once a period of time after the event is triggered, for example, during a search and when the user stops typing, the method is called to save resources for the request
- Throttling is when an event is frequently triggered and requested at regular intervals, similar to a long press of a button in a game, where the action is triggered at regular intervals