【前端手撕】防抖节流
碎碎念
好昨天是休息日。晚上吃了泰餐,泰奶狠狠发力于是两点半还睡不着,想了好多好多事情。
今天起来也累累的。有点担心自己的身体会不会又变差了最近还是严格控糖吧,以及也该恢复训练计划了!
今天在计划里加入了手写代码,都慢慢推进吧。
防抖
function debounce(fn, delay) { let timer = null const _debounce = function (...args){ // 剩余参数 if(timer) clearTimeout(timer) // 重复调用清除前面的 timer = setTimeout(() => { fn.apply(this, args) // 传参调用 }, delay) } return _debounce }节流
// 利用时间戳 function throttle(fn, delay) { let last = 0 const _throttle = function(...args) { const now = new Date().getTime() if (now - last >= delay) { fn.apply(this, args) last = now } } return _throttle }