Function throttling and stabilization
Foreword
In many cases, the triggering right of the event belongs to the user, and in some cases it will cause problems:
- Sending data to the background is frequently triggered by users, putting pressure on the server
- Some browser events: window.onresize, window.mousemove, etc. are triggered very frequently, which will cause browser performance problems
If you encounter these problems, then you need to use function throttling and anti-shake.
1. Function throttling (throttle)
Function throttling: After a function is executed once, it will only be executed a second time if it is greater than the set execution period .
There is a function that needs to be triggered frequently. From the perspective of optimizing performance, within the specified time, only the first time the function is triggered will take effect, and the subsequent ones will not take effect.
1. How to implement
The principle is to use the timestamp to judge whether the execution time of the callback has come, record the timestamp of the last execution, and then trigger the scroll event to execute the callback each time. In the callback, it is judged whether the interval between the current timestamp and the last execution timestamp has reached. Specify the time period, if it is, execute it, and update the timestamp of the last execution, and so on;
html,
body {
height: 500%; // make it appear scrollbar
}
function throttle(fn, delay) {
// record the last time the function was triggered
var lastTime = 0;
return function () {
// Record the time when the current function is triggered
var nowTime = Date.now();
if (nowTime - lastTime > delay) {
// fix this pointing problem
fn.call(this);
// synchronised time
lastTime = nowTime;
}
}
}
document.onscroll = throttle(function () { console.log('scroll event was triggered' + Date.now()) }, 200)
The above example uses the characteristics of closures - the value of the variable lastTime can be kept in memory for a long time.
2. Application scenarios of function throttling
Callbacks need to be triggered at certain intervals to control the frequency of function calls:
- DOM element drag and drop function implementation (mousemove)
- Search Lenovo (keyup)
- Calculate the distance the mouse moves (mousemove)
- Canvas simulates the artboard function (mousemove)
- The mousedown/keydown event of the shooting game (only one bullet can be fired per unit time)
- Listen to scroll events to determine whether to automatically load more at the bottom of the page: After adding debounce to the scroll, it will only be judged whether the bottom of the page is reached after the user stops scrolling; if it is throttle, as long as the page scrolls, it will be judged at intervals of time
2. Function debounce (debounce)
Anti-shake function: a function that needs to be triggered frequently. Within the specified time, only the last one will take effect, and the previous ones will not take effect.
1. How to implement
The idea is to call the function for the first time, create a timer, and run the code after a specified time interval. When the function is called a second time, it clears the previous timer and sets another. If the previous timer has already executed, this operation has no meaning. However, if the previous timer has not been executed, it is actually replaced by a new timer, and then delayed for a certain period of time before executing.
<button id='btn'>button</button>
<script type="text/javascript">
function debounce(fn, delay) {
// record the last delay
var timer = null;
return function () {
// clear the last delay
clearTimeout(timer)
timer = setTimeout(function () {
fn.apply(this)
} }, delay)
}
}
document.getElementById('btn').onclick = debounce(function () {
console.log('The click event was triggered' + Date.now())
}, 1000)
</script>
The above example also uses the feature of closures - the value of the variable timer can be kept in memory for a long time.
2. Application scenarios of function anti-shake
For continuous event response we only need to execute the callback once:
- Every time resize/scroll trigger statistics event
- Validation of text input (send an AJAX request for validation after continuous input of text, just validate once)
3. Summary
The core of function throttling and function debounce is actually to restrict a method from being triggered frequently, and the reason why a method is frequently triggered is mostly because of the monitoring callback of DOM events, which is also function throttling and anti-shake. Application scenarios in most cases.