ngStorage icon indicating copy to clipboard operation
ngStorage copied to clipboard

debounce watcher causing heavy load in ngUpgrade apps

Open sime opened this issue 8 years ago • 4 comments

The $rootScope.$watch() causes a high load in ngUpgraded apps (2.4.x).

When I comment out the following block, the DevTools timeline shows next to no activity.

https://github.com/gsklee/ngStorage/blob/c217d5bb01b4a79bb389d05a83513c89b5d34bf9/ngStorage.js#L206-L208

sime avatar Jan 30 '17 17:01 sime

Personally I think this is related to: https://github.com/angular/angular/pull/13540#issuecomment-267846406

The upgrade-adapter runs an angularjs digest cycle, when microtasks are empty. Unfortunately this lines of code above regularly start a new timeout - which in turn starts the digest cycle again.

bluegaspode avatar Sep 01 '17 22:09 bluegaspode

This describes the problem even better, but still unresolved: https://github.com/angular/angular/pull/15157

bluegaspode avatar Sep 01 '17 23:09 bluegaspode

The fix would be to give the $watch function a watchExpression as a first argument and a listener as a second. this would remove the need of the timeout as well:

$rootScope.$watch(function () {return $storage}, function () {
                 $storage.$apply();
               });

meDavid avatar Apr 08 '20 10:04 meDavid

Here's my shitty workaround:

diff --git a/node_modules/ngstorage/ngStorage.js b/node_modules/ngstorage/ngStorage.js
index 0bbdb69..15d138e 100644
--- a/node_modules/ngstorage/ngStorage.js
+++ b/node_modules/ngstorage/ngStorage.js
@@ -202,8 +202,10 @@
 
                 _last$storage = angular.copy($storage);
 
+                var setTimeout = window[window.Zone.__symbol__('setTimeout')];
+
                 $rootScope.$watch(function() {
-                    _debounce || (_debounce = $timeout($storage.$apply, 100, false));
+                    _debounce || (_debounce = setTimeout($storage.$apply, 100));
                 });
 
                 // #6: Use `$window.addEventListener` instead of `angular.element` to avoid the jQuery-specific `event.originalEvent`

Eugeny avatar Dec 20 '21 17:12 Eugeny