darkhorse
darkhorse

Reputation: 8782

Wait for the window to complete resizing itself, and then do something in Angular

So basically, I am trying to do some calculations when the window is being resized. Right now, my code looks like this:

var appWindow = angular.element($window);
appWindow.bind('resize', function () {
    // Do Something
});

However, right now the function runs upto 30 times sometimes, so its quite slow. Any way to fire it just once when the window is done resizing? Thanks!

Upvotes: 0

Views: 743

Answers (2)

Jacob King
Jacob King

Reputation: 196

I would try to track the window 'resize' event with a timeout and then run the function when it has been completely resized:

var resizing;
var appWindow = angular.element($window);
appWindow.bind('resize', function () {
    clearTimeout(resizing);
    resizing= setTimeout(function() {
      // Do Something
    }, 250);
});

This is not extremely elegant, you can also use the $timeout service Angular gives you.

Upvotes: 0

Joey
Joey

Reputation: 680

Here is a method for accomplishing this:

var resizeTimeout;

appWindow.bind('resize', function() {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(function() {
        // when the window stops resizing, this function will execute
    }, 200);
});

Basically, when the event fires it clears the existing timeout and then sets a timeout. When the window has stopped resizing, the last timeout created from the setTimeout call is not cleared, and therefore executes after the specified duration in milliseconds.

Upvotes: 2

Related Questions