本質是優化高頻率執行代碼的手段,好比 scroll keypress mousemove等事件。markdown
function debounce(func, wait) {
let timeout;
return function () {
let context = this; // 保存this指向
let args = arguments; // 拿到event對象
clearTimeout(timeout)
timeout = setTimeout(function(){
func.apply(context, args)
}, wait);
}
}
複製代碼
function throttled(fn, delay) {
let timer = null
let starttime = Date.now()
return function () {
let curTime = Date.now() // 當前時間
let remaining = delay - (curTime - starttime) // 從上一次到如今,還剩下多少多餘時間
let context = this
let args = arguments
clearTimeout(timer)
if (remaining <= 0) {
fn.apply(context, args)
starttime = Date.now()
} else {
timer = setTimeout(fn, remaining);
}
}
}
複製代碼
clearTimeout
和 setTimeout
實現。函數節流,在一段連續操做中,每一段時間只執行一次,頻率較高的事件中使用來提升性能