简体   繁体   中英

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM