Last active
January 21, 2020 08:48
-
-
Save Oikio/afeeaf28b343a1be3d76095c2ae8664a to your computer and use it in GitHub Desktop.
Debounce and throttle functions from https://remysharp.com/2010/07/21/throttling-function-calls
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
function debounce(fn, delay) { | |
var timer = null; | |
return function () { | |
var context = this, args = arguments; | |
clearTimeout(timer); | |
timer = setTimeout(function () { | |
fn.apply(context, args); | |
}, delay); | |
}; | |
} | |
function throttle(fn, threshhold, scope) { | |
threshhold || (threshhold = 250); | |
var last, | |
deferTimer; | |
return function () { | |
var context = scope || this; | |
var now = +new Date, | |
args = arguments; | |
if (last && now < last + threshhold) { | |
// hold on to it | |
clearTimeout(deferTimer); | |
deferTimer = setTimeout(function () { | |
last = now; | |
fn.apply(context, args); | |
}, threshhold); | |
} else { | |
last = now; | |
fn.apply(context, args); | |
} | |
}; | |
} |
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
function throttle<T, U>(fn: T extends Function ? T : Function, threshold = 1000, scope?: U) { | |
let last: number | |
let deferTimer: number | |
return function(this: any) { | |
const context = scope || this | |
const now = +new Date() | |
const args = arguments | |
if (last && now < last + threshold) { | |
// hold on to it | |
clearTimeout(deferTimer) | |
deferTimer = setTimeout(() => { | |
last = now | |
fn.apply(context, args) | |
}, threshold) | |
} else { | |
last = now | |
fn.apply(context, args) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment