Home > Article > Web Front-end > Introduction to the basic implementation methods of throttle valve and debouncing
This article brings you an introduction to the basic implementation methods of throttle valve and debouncing. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Throttle valvethrottle
The events triggered are executed in a periodic manner, not in real time. Like a dripping faucet.
function throttle (fn, delay) { // 利用闭包变量时效性 let timeout let arg return function () { arg = arguments if (!timeout) { timeout = setTimeout(() => { fn.apply(this, arg) timeout = null }, delay) } } } // demo /* var test = throttle(function (a) {console.log(a)}, 1000) test(1) // 不执行 test(2) // 不执行 test(3) => 3 test = null // 不需要时释放内存 */
Debounce debounce
Triggers N milliseconds after the last event, such as an elevator door.
function debounce (fn, delay){ let timeout return function(){ const args = arguments clearTimeout(timeout) timeout = setTimeout(() => { fn.apply(this, args) }, delay) } } // 用法同throttle
The above is the detailed content of Introduction to the basic implementation methods of throttle valve and debouncing. For more information, please follow other related articles on the PHP Chinese website!