After reading this How to delay the .keyup() handler until the user stops typing? post, we have grasped how to implement delays. However, is there any suggestion on how to cancel a delayed event?
Take a look at this
In the scenario given, I want nothing to display after pressing the cancel
button.
Yet, I am in need of a more versatile solution. One possibility could be to modify the delay()
function in a way similar to this:
delay(fn, ms, cancelCallback)
Within this setup, the cancelCallback
would serve as a method to terminate the delay. By cancelling the delay, we mean refraining from executing the fn()
and simply doing 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));
// Introducing 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>