Last Updated: February 13, 2017
· abhikandoi2000

Fix function being called twice on window resize

While using certain browsers, re-sizing the browser window calls the function associated with that event twice. Here is a simple fix for calling the function just once.

The basic idea is to set a timeout to call the function after a certain time (half second here, depends on the execution speed of browser), and then when the same function is called upon the second time by the browser, it will clear the function calling as described above. But at the same time it will set a timeout to call the same function again and hence the function is executed just once.

var timeoutId;
window.onresize = function(){
  //call the function after half second
  timeoutId = window.setTimeout(doSomething, 500);

function doSomething(){
console.log("You should see this once.");
  //do something here

3 Responses
Add your response


I am sorry but I don't exactly understand how is your code working. We first clear the time out and then set it to 500ms. So doSomething() is called for the first time, and then when browser again comes to onresize() function it clears the timer, then again sets it, so why is doSomething() function not being called second time.

over 1 year ago ·

Let us consider the two calls of the function onresize corresponding to the two event triggers.

The first time the function is called, window.clearTimeout(timeoutId) does nothing as timeoutId is not yet initialized. Now, a call to function doSomething will be made after a time interval of 500 milliseconds (notice the function is yet to be called). And the assignment

timeoutId = window.setTimeout(doSomething, 500);

will store a numerical id corresponding to the timeout for later use.

The second time the function is called, the previously declared timeout is cleared and since this happens within a time-gap of 500 milliseconds(which is a reasonable assumption given the speed of modern JavaScript engines) the function was never called. But after the statement:

timeoutId = window.setTimeout(doSomething, 500);

another timeout is defined and the function doSomething is called after 500 milliseconds.

So effectively the function doSomething is called only once.
Hope this makes the functioning clear.

over 1 year ago ·

This helped a great deal, created a quick dashboard with google charts and needed to resize all when the window was resized..
window.onresize = function(){

Did the trick.

over 1 year ago ·