Sometimes, we want to wait for the end of the resize event and only then perform an action with JavaScript.
In this article, we’ll look at how to wait for the end of the resize event and only then perform an action with JavaScript.
How to wait for the end of the resize event and only then perform an action with JavaScript?
To wait for the end of the resize event and only then perform an action with JavaScript, we use setTimeout
.
For instance, we write
const onResizeDone = () => {
// ...
};
let timer;
window.onresize = () => {
clearTimeout(timer);
timer = setTimeout(onResizeDone, 100);
};
to set window.onresize
to a function that calls clearTimeout
to clear the setTimeout
timer
.
Then we call setTimeout
with onResizeDone
with 100 to call it after 100 milliseconds after the resize event handler is called.
Conclusion
To wait for the end of the resize event and only then perform an action with JavaScript, we use setTimeout
.