Skip to content

throttle() function causes Angular to not get stable #983

Open
@pappkamerad

Description

@pappkamerad

When using your library with Angular, I noticed that the setTimeout() in your throttle() function is causing Angular to not get 'stable' for the given interval (default is 60s).

Angular considers itself 'unstable' when ZoneJS is seeing pending micro or macro tasks in the Angular zone. ('isStable' doc: https://angular.io/api/core/ApplicationRef#is-stable-examples)

The problem, as i understand it, here is that the throttle() gets executed within the Angular zone if Angular is present.

We use this 'isStable' flag for certain features that need to know if the given route has finished loading and the page rendering/processing is done.

So, as the general solution to this is, that you run your long running tasks outside of the Angular zone, my idea was to also run your throttle setTimeout function in a separate, new zone if there is window.Zone available.

Something like:

export default function throttle(fn, onThrottle, opts) {
  var context = this;
  var limit = opts.limit;
  var interval = opts.interval;
  var counter = 0;
  var timeoutId;
  var throttleZone = typeof Zone !== 'undefined' && Zone.root.fork({name: 'apm-throttle-zone'});

  return function () {
    counter++;

    if (typeof timeoutId === 'undefined') {
        var timeoutFn = function () {
          timeoutId = setTimeout(function () {
            counter = 0;
            timeoutId = undefined;
          }, interval);
        };

        if (throttleZone) {
          throttleZone.run(timeoutFn)
        } else {
          timeoutFn();
        }
    }

    if (counter > limit && typeof onThrottle === 'function') {
      return onThrottle.apply(context, arguments);
    } else {
      return fn.apply(context, arguments);
    }
  };
}

What do you guys think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions