1

I'm doing a few functions on $(window).resize(). One of the functions inside it, is a complex animation with lots of divs.

$window.resize(function() {
    // some functions
    doAnim();
}

the problem here is, that the resize() function triggers a lot. Is it possible to fire one function after the resize() is finished, that it doesnt fire a hundred times?

Cheers

supersize
  • 13,764
  • 18
  • 74
  • 133

2 Answers2

2

So, I believe this is a similar scenario when a user "type" something: you can't know when the user finished to compose a sentence, the same here, you don't know when the user has finished to resize; so what you can do is have an acceptable interval:

var idt;
$(window).resize(function() {
    if (idt) clearTimeout(idt);
    idt = setTimeout(doAnim, 500);
}

You can also use a closure to avoid to pollute the global scope with idt variable.

However the main point here is that every time the user resize the window, it set a timeout and clear the previous one: the doAnim function will be executed only if the user leave the window without resizing it for half second. Of course you can set your own delay.

ZER0
  • 24,846
  • 5
  • 51
  • 54
0

You can achieve it as shown below. This will call when you finish with resizing :

        var myTimer;
        $(window).resize(function() 
        {
            // some functions
            var interval = 500;
            clearInterval(myTimer);
            myTimer = setInterval(function () { doAnim(); }, interval);
        });

        function doAnim() 
        {
            clearInterval(myTimer);
            alert('Resized');
        }
SpiderCode
  • 10,062
  • 2
  • 22
  • 42