Open dave-wind opened 1 year ago
function debounce(fn, num = 300) { let self, timer = null; return function () { self = this; if (timer) { clearTimeout(timer); timer = null; } timer = setTimeout(function () { fn.apply(self, arguments) }, num) } } function throttle(fn, delay = 300) { let lasttime, now, timer = null, self, args; const excute = function () { fn.apply(self, args); lasttime = now; } return function () { self = this; args = Array.prototype.slice.call(arguments); now = new Date().getTime(); if (timer) { clearTimeout(timer); timer = null } if (lasttime) { const diff = delay - (now - lasttime); if (diff > 0) { // 操作非常频繁 就延迟执行 timer = setTimeout(function () { excute() }, delay) } else { excute() } } else { excute() } } }
节流与防抖