Created
October 10, 2019 03:04
-
-
Save somarlyonks/3c9a2127f1ffca43c4af54065923b650 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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