//防抖(debounce):触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。
const debounce = (func, delay = 200) => {
let timeout = null
return function () {
clearTimeout(timeout)
timeout = setTimeout(() => {
func.apply(this, arguments)
}, delay) }
}
const fetch = (e) => {
console.log('fetch', e)
}
const debounceSuggest = debounce(fetch, 500)
const btn1 = document.getElementById('btn1')btn1.onclick = function (e) {
debounceSuggest(e)
}
//节流(throttle):高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率。
const throttle = (func, delay = 200) => {
let timeout = null
return function () {
if (!timeout) {
timeout = setTimeout(() => {
func.apply(this, arguments)
clearTimeout(timeout)
timeout = null }, delay) }
}
}
const throttleSuggest = throttle(fetch, 500)
const btn2 = document.getElementById('btn2')
btn2.onclick = function (e) {
//触发方法
console.log("click")
throttleSuggest(e)
}
网友评论