节流
function throttle(fn, timer) { let time; return function() { if (time) return; time = setTimeout(() => { fn() time = null; }, timer) } }
防抖
function debounce(fn, time) { let timer; return function() { clearTimeout(timer); timer = setTimeout(() => { fn(); }, time) } }
节流第二种:
function throttle(fn, interval = 300) { let canRun = true; return function () { if (!canRun) return; canRun = false; setTimeout(() => { fn.apply(this, arguments); canRun = true; }, interval); }; }
节流第三种:
var throttleV2 = function(action, delay){ var statTime = 0; return function() { var currTime = +new Date(); if (currTime - statTime > delay) { action.apply(this, arguments); statTime = currTime ; } } } // example function resizeHandler() { console.log("resize"); } window.onresize = throttleV2(resizeHandler, 300);