Skip to content

Instantly share code, notes, and snippets.

@electerious
Created February 1, 2019 11:32
Show Gist options
  • Save electerious/117529b582d5957411fe0b6c2c6faa8b to your computer and use it in GitHub Desktop.
Save electerious/117529b582d5957411fe0b6c2c6faa8b to your computer and use it in GitHub Desktop.
const throttle = (fn, threshold) => {
let last
let timeout
return (...args) => {
const now = Date.now()
const shouldDelay = last && now < last + threshold
const delay = shouldDelay === true ? threshold - (now - last) : 0
const execute = () => {
last = now
fn(...args)
}
clearTimeout(timeout)
timeout = setTimeout(execute, delay)
}
}
@electerious
Copy link
Author

electerious commented Feb 1, 2019

Example:

const fn = (text) => console.log(text)
const tfn = throttle(fn, 200)

tfn('hello') // hello
setTimeout(() => tfn('hello'), 100)
setTimeout(() => tfn('hello'), 110) // hello (after 200ms)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment