Anti-shake - the function will only be executed once n seconds after the high-frequency event is triggered . If the high-frequency event is triggered again within n seconds, the time will be recalculated;
Idea: cancel the previous delay call method every time an event is triggered.
function debounce(fn) {
let timeout = null
// Create a marker to store the return value of the timer
return function() {
clearTimeout(timeout)
// Whenever the user enters, clear the previous setTimeout
timeout = setTimeout(() => {
// Then create a new setTimeout, so that the time after entering the character can be guaranteed
If there are still characters input within the interval interval, the fn function will not be executed
fn.apply(this, arguments)
}, 500)
}
}
function sayHi() {
console.log ( ' Successful anti-shake' )
}
var inp = document.getElementById('inp')inp.addEventListener('input', debounce(sayHi))
Throttling - high-frequency event triggers, but only executes once in n seconds , so throttling will dilute the execution frequency of the function.
Idea: Every time an event is triggered, it is judged whether there is a delay function waiting to be executed.
function throttle(fn) {
let canRun = true // save a token through the closure
return function() {
if (!canRun) return
// At the beginning of the function, judge whether the flag is true, if not true, return
canRun = false // immediately set to false
setTimeout(() => {
// Put the execution of the function passed in from outside in setTimeout
fn.apply(this, arguments)
// Finally, after the execution of setTimeout is completed, set the flag to true (key) to indicate that the next loop can be executed. When the timer is not executed, the flag is always false and is returned at the beginning
canRun = true
}, 500)
}
}
function sayHi(e) {
console.log(e.target.innerWidth,e.target.innerHeight)
}
window.addEventListener('resize', throttle(sayHi))