Skip to content

Instantly share code, notes, and snippets.

@TimRChen
Created March 12, 2020 10:46
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 TimRChen/f6ee4629e77ea2d72c1abe6f63ff3f62 to your computer and use it in GitHub Desktop.
Save TimRChen/f6ee4629e77ea2d72c1abe6f63ff3f62 to your computer and use it in GitHub Desktop.
simple throttle demo by timrchen
const $box = document.querySelector(".mouse-move-box");
let timer = null;
const options = {
capture: false
};
const listener = e => {
const { x, y } = e;
const str = `x: ${x}, y: ${y}`;
console.log(str);
};
function throttle(fn, wait) {
let start = Date.now();
return e => {
if (Date.now() - start >= wait) {
clearTimeout(timer)
timer = setTimeout(fn.bind(this, e), wait);
start = Date.now()
}
};
}
const wait = 100;
$box.addEventListener("mousemove", throttle(listener, wait), options);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment