Skip to content

Instantly share code, notes, and snippets.

@zerosrat
Last active March 30, 2019 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerosrat/9c0549cd34d4a44c5d2e3e769efc09e7 to your computer and use it in GitHub Desktop.
Save zerosrat/9c0549cd34d4a44c5d2e3e769efc09e7 to your computer and use it in GitHub Desktop.
function debounce(fn, ms, immediate) {
let id = null
return function(...args) {
id && clearTimeout(id)
if (immediate) {
const callNow = id === null
id = setTimeout(() => id = null, ms)
callNow && fn.apply(this, args)
} else {
id = setTimeout(() => {
fn.apply(this, args)
}, ms)
}
}
}
function throttle(fn, ms) {
let id = null
return function(...args) {
if (!id) {
id = setTimeout(() => {
id = null
}, ms)
fn.apply(this, args)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment