节流和防抖---快来看,简单学

109 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第6天,点击查看活动详情

Talking is cheap show me the code 防抖

function debounce (fn, delay = 200) { let timeout; return function() { // 重新计时 timeout && clearTimeout(timeout); timeout = setTimeout(fn.bind(this), delay, ...arguments); } }

const handlerChange = debounce(function () {alert('更新触发了')})

// 绑定监听 document.querySelector("input").addEventListener('input', handlerChange);

节流

function throttle (fn, threshhold = 200) { let timeout; // 计算开始时间 let start = new Date(); return function () { // 触发时间 const current = new Date() - 0; timeout && clearTimeout(timeout); // 如果到了时间间隔点,就执行一次回调 if (current - start >= threshhold) { fn.call(this, ...arguments); // 更新开始时间 start = current; } else { // 保证方法在脱离事件以后还会执行一次 timeout = setTimeout(fn.bind(this), threshhold, ...arguments); } } }

let handleMouseMove = throttle(function(e) { console.log(e.pageX, e.pageY); })

// 绑定监听 document.querySelector("#panel").addEventListener('mousemove', handleMouseMove); 复制代码

从代码上看不难发现,节流只是在防抖的基础上加了时间差的判断,多穿了件马甲而已。