angular: Usage of `queueMicrotask` in recursive function from outside zone task can cause infinite loop

Which @angular/* package(s) are the source of the bug?

zone.js

Is this a regression?

No

Description

TOTAL SITE FAILURE

We came across a major compatibility issue on several customer sites running Angular. Our code is utilizing queueMicrotask as part of initialization. When opening an XMLHttpRequest within a subsequent microtask the browser CPU spikes due to recursively calling queueMicrotask. This only happens on Zone-enabled sites.

To reproduce, paste the following code into the console on one of the following sites: LandsEnd.com, Avery.com, PapaGinos.com:

(function() {
  "use strict";
  let _isDispatching = false;
  function run() {
    function dispatch(event) {
      console.log("in dispatch for loggerString", event);
      if (_isDispatching) {
        console.log("already dispatching, queuing string", event);
        queueMicrotask(() => dispatch(event));
        console.log("queued string", event);
        return;
      }
      _isDispatching = true;
      if (event === "init") {
        dispatch("extra event");
        const xhr = new XMLHttpRequest();
        xhr.open("GET", "google.com", true);
      }
      _isDispatching = false;
    }
    dispatch("init");
  }
  run();
})();

In attempting to create as small a reproduction as possible, I used a stock CLI app and was able to recreate the issue with a larger piece of code. However, once narrowing down to this smaller example code, we weren’t able to replicate in a toy app. Happy to attempt to help find out more about the incompatibility, but right now this is as far as we were able to get in terms of narrowing down the use case.

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

Infinite loop/stuck in microtask queueing.

Please provide the environment you discovered this bug in (run ng version)


Anything else?

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 24 (23 by maintainers)

Most upvoted comments

Another option: intentionally wrap all your logic (run() in your example) in a Zone task (if Zone is present on the page). This provides a guarantee that the queue won’t flush prematurely.

Follow-up: The strange thing here is this edgecase was hit after removing an async/await from a higher level function that in turn kicked off the initialization, which hit this dispatch recursion. But the script load sequence wouldn’t have changed.

This could be because native async/await isn’t patchable by ZoneJs but requires downleveling to promises. Native Async/await would have kept you out of ZoneJs-land and prevented whatever microtask in there from being drained synchronously by ZoneJS. Just guessing but likely something along those lines.