Skip to content

Instantly share code, notes, and snippets.

@havenchyk
Created October 6, 2017 17:24
Show Gist options
  • Save havenchyk/455e64bc730abe89f8d4fe458d7cf5c5 to your computer and use it in GitHub Desktop.
Save havenchyk/455e64bc730abe89f8d4fe458d7cf5c5 to your computer and use it in GitHub Desktop.
throttle with recurring
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