函数的节流和防抖
防抖函数:将多次触发变成最后一次触发
function debounce(fn,wait){ let timer = null; return function (){ let arg = arguments; if(timer){ clearTimeout(timer); timer = null; } timer = setTimeout(()=>{ fn.apply(this,arg) },wait) } } function clg(){ console.log('clg') } window.addEventListener('resize',debounce(clg,1000))
节流函数:将多次执行变成每隔一个时间节点去执行的函数
function throttle(fn,time){ let lastTime = null; return function(){ let nowTime = Date.now(); if(nowTime - lastTime > time || !lastTime){ fn(); last = nowTime } } } function sayHi(){ console.log('hi') } setInterval(throttle(sayHi,1000),500)