Created
June 13, 2018 14:36
-
-
Save airton/a60294f66e439673941d83ef7f3deae3 to your computer and use it in GitHub Desktop.
Throttling and debouncing in JavaScript
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
const area = document.getElementById("area"); | |
const state = { | |
throttled: { | |
x: 0, | |
y: 0, | |
}, | |
debounced: { | |
x: 0, | |
y: 0, | |
} | |
} | |
area.addEventListener("mousemove", coordUpdater("r")); | |
area.addEventListener("mousemove", throttled(200, coordUpdater("t"))); | |
area.addEventListener("mousemove", debounced(200, coordUpdater("d"))); | |
function handler(e) { | |
mouseToState(e); | |
updateDisp(e); | |
} | |
function coordUpdater(prefix) { | |
const x = document.getElementById(`${prefix}x`); | |
const y = document.getElementById(`${prefix}y`); | |
return function (e) { | |
x.innerText = e.clientX; | |
y.innerText = e.clientY; | |
} | |
} | |
function throttled(delay, fn) { | |
let lastCall = 0; | |
return function (...args) { | |
const now = (new Date).getTime(); | |
if (now - lastCall < delay) { | |
return; | |
} | |
lastCall = now; | |
return fn(...args); | |
} | |
} | |
function debounced(delay, fn) { | |
let timerId; | |
return function (...args) { | |
if (timerId) { | |
clearTimeout(timerId); | |
} | |
timerId = setTimeout(() => { | |
fn(...args); | |
timerId = null; | |
}, delay); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment