April 21, 2021 • 2 min read
We are implementing a text editor with a Google-Docs-like draft system, where content gets saved server-side when the user stops typing for a second.
We are going to use the keyup event and window.setTimeout .
// Declare a new variable that will get reassigned later with the timeout id
let timerId;
// Get the DOM Node of the input area and listen for a keyup event
document.querySelector("textarea").addEventListener("keyup", () => {
// Clear timeout to callback, doesn't do anything on first run since timerId is undefined
clearTimeout(timerId);
// Set timerId to fire callback in one second, unless another keyup event is triggered
timerId = window.setTimeout(renderCurrentTime, 1000);
});
// Callback that will get fired 1s after typing
function renderCurrentTime() {
// TODO: Save note to server
document.querySelector("time").textContent = new Date().toLocaleString();
}
The key to this snippet is that the timerId has to be set declared in the scope of the keyup callback, in order to be reassigned to the new timeout id every time the keyup callback is fired again.