在必定時間內執行一次,若是在此時間內再次觸發,則從新計時app
const debounce = (func, timeout, immediate = false) => { let timer = null; return function (...args) { if (!timer && immediate) { func.apply(this, args); } if (timer) { clearTimeout(timer); } timer = setTimeout(() => { func.apply(this, args); }, timeout); } }
在必定時間內執行一次,若是在此時間內再次觸發,則會攔截不執行this
const throttle = (func, timeout) => { let timer = null; return function (...args) { if (!timer) { timer = setTimeout(() => { timer = null; func.apply(this, args); }, timeout); } } }