called
, and set it to true
once the function is called for the first time, preventing it from being called again.this
context changed (such as in an event listener), the function
keyword must be used, and the supplied function must have the context applied....
) operator.const once = fn => {
let called = false;
return function(...args) {
if (called) return;
called = true;
return fn.apply(this, args);
};
};
const startApp = function(event) {
console.log(this, event); // document.body, MouseEvent
};
document.body.addEventListener('click', once(startApp));
// only runs `startApp` once upon click
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️