Created
March 12, 2020 10:46
-
-
Save TimRChen/f6ee4629e77ea2d72c1abe6f63ff3f62 to your computer and use it in GitHub Desktop.
simple throttle demo by timrchen
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 $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