From this How to delay the .keyup() handler until the user stops typing? question we've learned how to create delays. But any ideas on how do I cancel delayed event?
Check this out
In this example I don't want anything to be printed out after clicking the cancel
button.
But I need more extensible solution. The solution might be to modify the delay()
function somehow like this
delay(fn, ms, cancelCallback)
In here the cancelCallback
would be a function that cancels the delay. By cancels the delay I mean to not call the fn()
and just do nothing.
const inputElement = document.getElementById('input');
const buttonElement = document.getElementById('button');
const pElement = document.getElementById('p');
const delayInMs = 2000; // 2s delay
const delay = function (fn, ms) {
let timer = 0;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(fn.bind(this, ...args), ms || 0);
};
};
const print = text => pElement.innerHTML = text;
const handleKeyUp = e => print(e.target.value);
inputElement.addEventListener('keyup', delay(handleKeyUp, delayInMs));
// Some new logic
const cancelDelay = () => {};
inputElement.addEventListener('click', cancelDelay);
<input id="input" />
<button id="button">Cancel</button>
<br />
<h6>You typed:</h6>
<p id="p"></p>