I made a debounce function in Vanilla JS to understand how debouncing function works.
<!-- index.html -->
<div>
<input id="text" type="text" />
</div>
// index.js
const textLog = (e) => {
console.log('--textLog start--');
console.log(e.target);
console.log(e.currentTarget); // 1. e.currentTarget is null at this point
console.log('--textLog end--');
};
const debounce = (func, wait) => {
let timeOutId;
return (arg) => {
console.log('target', arg.target);
console.log('currentTarget', arg.currentTarget); // 2. arg.currentTarget exists at this point
if (timeOutId) {
clearTimeout(timeOutId);
}
timeOutId = setTimeout(() => {
func.call(null, arg);
}, wait);
};
};
const debounceLogging = debounce(textLog, 1000);
const input = document.getElementById('text');
input.addEventListener('input', debounceLogging);
This is just logging the enterd value of the input after user stopped typing for a second (1000 ms).
StackBlitz: https://stackblitz.com/edit/js-mcneev?file=index.js
In textLog(), I initially used e.currentTarget.value to get the enterd value to the input, but it threw an error saying Cannot read properties of null (reading 'value').
Then I replaced currentTarget with target and it worked as I intended.
What I know about a difference between target and currentTarget is the element that is reffereing.
However, to me, this error happend because of other cause.
- I checked inside the function returned from
debounce(),e.targetande.currentTargetboth have values inside of them. - But inside the
textLog()called inside of the returned function,e.targetis not null, bute.currentTargetis null.
Could anyone tell me what caused thie error or why this error happend? Thank you