Image stabilization
When an event is continuously triggered and no event is triggered again within a certain period of time, the event handler will execute once. If the event is triggered again before the set time, the delay will start again. That is, when a user keeps firing the function, and the interval between firing the function is shorter than the specified time, the anti-shake condition will only be executed once.
function debounce(fn, wait) {
var timeout = null; // Define a timer
return function() {
if(timeout ! = =null) {clearTimeout(timeout); }// Clear the timer
timeout = setTimeout(fn, wait); }}// handle the function
function handle() {
console.log(Math.random());
}
// Click the event
window.addEventListener('click', debounce(handle, 1000));
Copy the code
The throttle
Ensure that the event handler is called only once in a certain period of time when an event is continuously fired. This means that if a user keeps firing the function and each firing is less than the specified value, the function throttling will be called once in a while. There are two main ways to implement function throttling: timestamps and timers
/ / timestamp
var throttle = function(func, delay) {
var prev = Date.now();
return function() {
var context = this; / / this point to the window
var args = arguments;
var now = Date.now();
if (now - prev >= delay) {
func.apply(context, args);
prev = Date.now(); }}}function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));
/ / timer
var throttle = function(func, delay) {
var timer = null;
return function() {
var context = this;
var args = arguments;
if(! timer) { timer =setTimeout(function() {
func.apply(context, args);
timer = null; }, delay); }}}function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));
Copy the code
var throttle = function(func, delay) {
var timer = null;
var startTime = Date.now(); // Set the start time
return function() {
var curTime = Date.now();
var remaining = delay - (curTime - startTime); // The remaining time
var context = this;
var args = arguments;
clearTimeout(timer);
if (remaining <= 0) { // Execute immediately for first time
func.apply(context, args);
startTime = Date.now();
} else {
timer = setTimeout(func, remaining); // Cancel the current counter and evaluate the remaining}}}function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));
Copy the code