Created
October 6, 2017 17:24
-
-
Save havenchyk/455e64bc730abe89f8d4fe458d7cf5c5 to your computer and use it in GitHub Desktop.
throttle with recurring
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const throttleWithRecurring = function(fn, delay, options = {}) { | |
let timeoutId | |
let lastTimeCalled | |
let lastArguments | |
const startLoop = function(...args) { | |
lastArguments = args | |
if (!timeoutId) { | |
fn(...args) | |
timeoutId = setTimeout(() => { | |
timeoutId = null | |
if (options.recurring) { | |
startLoop(...args) | |
} else if (lastTimeCalled) { | |
fn(...args) | |
} | |
}, delay) | |
} else { | |
lastTimeCalled = new Date() | |
} | |
} | |
startLoop.flush = function() { | |
startLoop.cancel() | |
startLoop(...lastArguments) | |
} | |
startLoop.cancel = function() { | |
clearTimeout(timeoutId) | |
timeoutId = null | |
} | |
return startLoop | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment