在實際應用場景中,我們經常遇見高頻調用函數,導致瀏覽器的消耗,但我們可以根據實際需求使用防抖
和節流
函數。
1.防抖
釋義:在限定時間
內,只執行一次
函數。如果事件再次觸發,則重新計時,計時完畢再執行函數。
//非立即執行版
function debounce(func, wait) {
let timeout;
return function (event) {
// console.log(event)
let _this = this
let _args = arguments
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(() => {
func.apply(_this, _args)
}, wait)
}
}
//立即執行版,即首先加載一次
function debounce2(func, wait) {
let timeout;
return function (event) {
// console.log(event)
let _this = this
let _args = arguments
if (timeout) {
clearTimeout(timeout)
}
console.log(timeout)
let now = !timeout
timeout = setTimeout(() => {
timeout = null
}, wait)
if (now) func.apply(_this, _args)
}
}
2.節流
釋義:如果持續觸發事件,在一定時間只執行一次函數。
function throttle(func, wait) {
let isReady = true
return function () {
let _this = this
let _args = arguments
if (!isReady) {
return
}
isReady = false
timeout = setTimeout(() => {
isReady = true
func.apply(_this, _args)
}, wait)
}
}