How can I use throttling with getting an event target?

By referring to this site, 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);
    }
}


I want use throttled function like this.

item.addEventListener('click', throttled(2000, func(e.target)));


I have to use this to get the value of e.target.
However, if you write this code, the throttled function will not work properly.

item.addEventListener('click', (e) => {throttled(2000, func(e.target))});


How can I get the throttled function to work properly while getting targeted click events?

Answers:

Answer

Your throttled function will return a wrapper function around your original event handler. It will pass whatever arguments it received when now - lastCall >= delay to the fn callback function.
This is this wrapper function that you will add as an event handler, i.e the return value of throttled().

So all you need to pass to throttled is a normal event handler, i.e the same you would have passed to the event listener:

// 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

Or as one-liner onclick = throttled(2000, evt => console.log(evt.target));

Answer

Your throttled function expects a function as a second parameter.

let's assume func simply logs e.target to the console, you could write:

item.addEventListener('click', throttled(2000, func));

with

const func = (e) => console.log(e.target);

Or if you want everything in one line:

item.addEventListener('click', throttled(2000, (e) => func(e.target)));

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.