I have a DOM element btn and have function with setTimeout which listens on this element. I want to remove my listener while function is running to prevent multiple calls of setTimeout and time overlapping, but this in my callback function is window? I tried to use bind but it's not working
const checkTable = () => {
this.removeEventListener('click', checkTable);
console.log(this); // i get "window"
setTimeout(() => {
//some code
}, 3000);
};
const app = () => {
const checkBtn = document.querySelector('.check-btn');
checkBtn.addEventListener('click', checkTable.bind(checlBtn))
};
app();
and the same result with onclick event
You can't call .bind() on an arrow function. Arrow functions are used to automatically use the this value from where it's defined. For this to work, your checkTable needs to be a "normal" function.
function checkTable() {
this.removeEventListener('click', checkTable);
console.log(this); // i get "window"
setTimeout(() => {
//some code
}, 3000);
}