throttle implementation

node v10.24.1
version: 0.0.2
endpointsharetweet
//let _throttle = require("lodash/throttle") let lastTime; function fn(...args) { console.log(args, Date.now()); if (!lastTime) lastTime = Date.now(); else console.log("diff:", Date.now() - lastTime); } var fnThrottled = throttle(fn, 200); function throttle(fn, wait) { let lastCall, timer; return function() { let now = Date.now(); if (lastCall && now < lastCall + wait) { clearTimeout(timer); timer = setTimeout(() => { lastCall = now; fn.apply(this, arguments); }, wait); } else { lastCall = now; fn.apply(this, arguments); } }; } fnThrottled(1, 2, 3); fnThrottled(1, 2, 3); fnThrottled(1, 2, 3); fnThrottled(1, 2, 3); fnThrottled("a", "b", "c");
Loading…

no comments

    sign in to comment