Getting the user’s browser window size is super easy to do with jQuery. Just a simple one line of code gives us a width or height value.
var width = $(window).width()
var height = $(window).height()
However there’s one caveat. If we are running this code while the user is resizing the browser window we’ll get new values all the time as the window size changes. This depends on the browser, but for example Safari works this way.
If we would like to trigger a complex functionality for example a network call based on the changed window size this would lead to a very bad performance. We would quickly end up into a situation of launching tens of calls in a rapid sequence.
The obious answer to this problem is to filter out all the new values for the window size except the last one. So we’ll need to run the filtering until a user has stopped resizing the window.
We can do this filtering simply by setting a time threshold after which we conclude that the user has finished resizing the window.
Code for filtering excessive events
We can use jQuery to listen window resize events. When an event is detected we’ll first cancel the timeout to make sure we’ll get a fresh start.
Then we’ll setup a new timer. It will execute a function once the timer expires. That will happen after
resizeThreshold milliseconds. The function stores the new width and height values.
This method can be also called like
$(window).on("resize", handler). This gives us a nice option to turn the event listening also off by removing the event handler