?防抖debounce
// 手寫防抖
function debounce(fn, delay = 200) {// timer 在閉包中let timer = null// 返回一個函數return function(...args) {if (timer) {clearTimeout(timer) // 清空上次的值}timer = setTimeout(() => {fn.apply(this, args) // 透傳 this 和函數參數}, delay)}
}
節流throttle
// 手寫節流
function throttle(fn, delay = 100) {// timger 在閉包中let timer = null// 返回一個函數return function(...args){ // 當我們發現這個定時器存在時,則表示定時器已經在運行中,還沒到該觸發的時候,則 returnif (timer) {return}// 定時器不存在了,說明已經觸發過了,重新計時timer = setTimeout(()=>{fn.apply(this, args) // 透傳 this 和返回函數的參數,因為event傳遞給了throttle返回的函數timer = null}, delay)}
}