When triggering a callback from event like keyup, it’s possible to fire a ton of events and if they fetch something from a server, they can queue up and take time and then come back in different order.

That’s why it’s important to debounce – or cancel – the earlier attempts.

The debounce logic works like this. You store timeout in your model/view/class.

If one exists when you’re triggering your function, clear the previous one and then set a new one to trigger after a delay, here it’s 300ms.

if (timeout) clearTimeout(timeout);
timeout = setTimeout(async () => {
	doYourThing()
}, 300);

This means the code will wait for 300ms before running doYourThing and if it’s triggered again before it happens, it will cancel all the previous attempts, only resulting in one.