Skip to content

Instantly share code, notes, and snippets.

@somarlyonks
Created October 10, 2019 03:04
Show Gist options
  • Select an option

  • Save somarlyonks/3c9a2127f1ffca43c4af54065923b650 to your computer and use it in GitHub Desktop.

Select an option

Save somarlyonks/3c9a2127f1ffca43c4af54065923b650 to your computer and use it in GitHub Desktop.
const debounce = (f, time) => {
let debounced
return function (...args) {
const actor = () => f.apply(this, args)
clearTimeout(debounced)
debounced = setTimeout(actor, time)
}
}
const throttle = (f, time) => {
let throttled
let timeStamp
return function (...args) {
const actor = () => {
timeStamp = Date.now()
f.apply(this, args)
}
clearTimeout(throttled)
throttled = setTimeout(actor, timeStamp && (time - (Date.now() - timeStamp)))
}
}
// test
const testcase = {
data: {
x: 1
},
onDebounced: debounce(function (y, z) {
console.log('debounced', this.data.x, y, z)
}, 1000),
onThrottled: throttle(function (y, z) {
console.log('throttled', this.data.x, y, z)
}, 1000)
}
const test = f => Array(10).fill(0).forEach((_, i) => setTimeout(() => f(2, 3), 300 * i))
test(testcase.onDebounced.bind(testcase))
test(testcase.onThrottled.bind(testcase))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment