UNPKG

m_throttle

Version:

节流/防抖

30 lines (29 loc) 896 B
// 定时器 + 时间戳版本 // 下面我们来个加强版本的, 这个版本是结合了定时器和时间戳, 在我们鼠标移出监听区域后, 还会再执行一次函数 module.exports.throttle = (fn, wait) => { let time = 0, timer = null return function () { let now = Date.now() let args = arguments if (now - time > wait) { fn.apply(this, args) time = now } else { timer && clearTimeout(timer) timer = setTimeout(() => { fn.apply(this, args) time = now }, wait) } } } module.exports.debounce = (fn, delay) => { let timer = null return function () { let args = arguments clearTimeout(timer) timer = setTimeout(() => { fn.apply(this, args) }, delay) } }