通过引用本网站, https://codeburst.io/throttling-and-debouncing-in-javascript-646d076d0a44
throttled(delay, fn) {
let lastCall = 0;
return function (...args) {
const now = (new Date).getTime();
if (now - lastCall < delay) {
return;
}
lastCall = now;
return fn(...args);
}
}
我想像这样使用 throttle 功能。
item.addEventListener('click', throttled(2000, func(e.target)));
我必须使用它来获取 e.target 的值。
但是,如果您编写此代码, throttle 功能将无法正常工作。
item.addEventListener('click', (e) => {throttled(2000, func(e.target))});
如何在获取目标点击事件的同时使 throttle 功能正常工作?
最佳答案
您的throttled
函数将返回一个围绕您的原始事件处理程序的包装函数。它会将 now - lastCall >= delay
时收到的任何参数传递给 fn
回调函数。
这是您将作为事件处理程序添加的包装函数,即 throttled()
的返回值。
因此,您需要传递给 throttled
的只是一个普通的事件处理程序,即您将传递给事件监听器的相同内容:
// let's be a bit verbose
// our event handler
function handleevent(evt) {
console.log(evt.clientX); // logging the clientX here because evt.target is a big object for SO's console.
}
// the wrapper function
const myThrottledFunc = throttled(2000, handleevent);
// we add the wrapper as event handler
addEventListener('click', myThrottledFunc);
function throttled(delay, fn) {
let lastCall = 0;
return function wrapper(...args) {
const now = (new Date).getTime();
if (now - lastCall < delay) {
return;
}
lastCall = now;
return fn(...args);
}
}
click anywhere
或者作为一行 onclick = throttled(2000, evt => console.log(evt.target));
关于javascript - 如何使用 throttle 来获取事件目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54141738/