Home >Web Front-end >JS Tutorial >Easily understand the use of function anti-shake and throttling
Function anti-shake and throttling, this knowledge point is more likely to be asked in interviews.
The non-immediate execution version of anti-shake can be understood as executing a function once after n time. The immediate execution version of anti-shake is to execute a function immediately.
/** * @desc 函数防抖 * @param {Function} func 函数 * @param {Number} wait 延迟执行毫秒数 * @param {Boolean} immediate true 表示立即执行,false 表示非立即执行 */ function debounce(func, wait, immediate) { let timeout return function () { let context = this let args = arguments if (timeout) { clearTimeout(timeout) } if (immediate) { let callNow = !timeout timeout = setTimeout(() => { timeout = null }, wait) if (callNow) { typeof func === 'function' && func.apply(context, args) } } else { timeout = setTimeout(() => { typeof func === 'function' && func.apply(context, args) }, wait) } } }
Throttling can be understood as executing a function every n times.
/** * @desc 函数节流 * @param {Function} func 函数 * @param {Number} wait 延迟执行毫秒数 * @param {Boolean} type true 表示时间戳版,false 表示定时器版 */ function throttle(func, wait, type) { let previous let timeout if (type) { previous = 0 } else { timeout } return function () { let context = this let args = arguments if (type) { let now = Date.now() if (now - previous > wait) { typeof func === 'function' && func.apply(context, args) previous = now } } else { if (!timeout) { timeout = setTimeout(() => { timeout = null typeof func === 'function' && func.apply(context, args) }, wait) } } } }
Use the text box to enter text to demonstrate, if the time is set to 1s, the user continues to input text , if it is non-immediate anti-shake, the function will be executed 1s after the input is stopped, and it will be executed only once. If it is immediate anti-shake, the function will be executed immediately, and it will be executed only once. Throttling means executing a function every second, possibly multiple times, during user input.
The anti-shake function and throttling function in the following code are called 10000000 times, but the anti-shake function will only be executed once, but there are many throttling functions. times.
let debounceCallback = debounce(function () { console.log('debounceCallback') }, 1000, false) for (let i = 0; i < 10000000; i++) { debounceCallback() } let throttleCallback = throttle(function () { console.log('throttleCallback') }, 1000, false) for (let i = 0; i < 10000000; i++) { throttleCallback() }
Recommended tutorial: "JS Tutorial"
The above is the detailed content of Easily understand the use of function anti-shake and throttling. For more information, please follow other related articles on the PHP Chinese website!