Created
June 18, 2018 17:13
-
-
Save jackson-sandland/ecfe0ad5c05e9711d42d2f6d4b2f8c61 to your computer and use it in GitHub Desktop.
This file contains 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
// decorator to only allow function call after the timer is done. | |
const throttle = (func, delay) => { | |
let timeout; | |
return function() { | |
const context = this; | |
const args = arguments; | |
if (!timeout) { | |
func.apply(context, args); | |
timeout = true; | |
setTimeout(() => timeout = false, delay); | |
} | |
} | |
} | |
// decorator to catch the last fired event when throttling | |
const throttle = (func, delay) => { | |
let lastRan; | |
return function() { | |
const context = this; | |
const args = arguments; | |
if (!lastRan) { | |
func.apply(context, args); | |
lastRan = Date.now(); | |
} else { | |
setTimeout(function(){ | |
if ((Date.now() - lastRan) >= delay) { | |
func.apply(context, args); | |
lastRan = Date.now(); | |
} | |
}, delay - (Date.now() - lastRan)); | |
} | |
} | |
} | |
// decorator to queue all invocations and execute them at each timeout | |
const throttle = (func, delay) => { | |
let lastRan; | |
function wrapper() { | |
const context = this; | |
const args = arguments; | |
wrapper.calls.push(args); | |
if (!lastRan) { | |
func.apply(context, args); | |
wrapper.calls.shift(); | |
lastRan = Date.now(); | |
} else { | |
const queue = function() { | |
if (wrapper.calls.length > 0) { | |
if ((Date.now() - lastRan) >= delay) { | |
setTimeout(function() { | |
func.apply(context, args); | |
wrapper.calls.shift(); | |
lastRan = Date.now(); | |
}, delay - (Date.now() - lastRan)); | |
} | |
} | |
setTimeout(queue, delay); | |
} | |
queue(); | |
} | |
} | |
wrapper.calls = []; | |
return wrapper; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment