一个函数执行一次后,只有大于设定的执行周期才会执行第二次.函数
function throttle(fn, delay) { // 记录上一次函数触发的时间 var lastTime = 0 return function () { // 记录当前函数触发时间 var nowTime = Date.now() if (nowTime - lastTime > delay) { fn() lastTime = nowTime } } }
document.onscroll = throttle(function () { console.log('事件触发' + Date.now()) }, 200)
一个须要频繁触发的函数 在规定事件内 只让最后一次生效 前面的不生效测试
function debounce(fn, delay) { // 记录上一次延时器 var timer = null return function () { // 清除上一次的延时器 clearTimeout(timer) // 从新设置新的延时器 timer = setTimeout(() => { fn() }, delay) } }
<button id="btn"> 按钮</button>
document.getElementById('btn').onclick = debounce(function () { console.log('点击事件被触发了') }, 1000)