Function image stabilization
Trigger the same event multiple times within a short period of time. Execute only the last time or the first time.
/ * * *@param {Function} F sub n target function *@param {Number} Time Delay number of milliseconds *@param {Boolean} Immediate true - Immediate execution false - Delay execution *@description Anti - shake function */
export function debounce(fn, time, immediate = true) {
let timer
return function() {
const that = this
const args = arguments
if (timer) clearTimeout(timer)
if (immediate) {
constcallNow = ! timer timer =setTimeout(() = > {
timer = null
}, time)
if (callNow) {
fn.apply(that, args)
}
} else {
timer = setTimeout(() = > {
fn.apply
}, time)
}
}
}
Copy the code
Function of the throttle
Events are fired continuously but the function is executed only once in n seconds. That is, 2 executions in 2n seconds, throttling literally dilutes the execution frequency of the function.
/ * * *@param {Function} F sub n target function *@param {Number} Time Delay number of milliseconds *@param {Boolean} Type 1- Immediate execution, 2- no immediate execution *@description The throttle function */
function throttle(fn, time, type) {
let previous = 0
let timeout
return function() {
let that = this
let args = arguments
if (type === 1) {
let now = Date.now()
if (now - previous > time) {
fn.apply(that, args)
previous = now
}
} else if (type === 2) {
if(! timeout) { timeout =setTimeout(() = > {
timeout = null
fn.apply(that, args)
}, time)
}
}
}
}
Copy the code