11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ciconst common = require('../common');
31cb0ef41Sopenharmony_ciconst assert = require('assert');
41cb0ef41Sopenharmony_ci
51cb0ef41Sopenharmony_ciconst { MessageChannel } = require('worker_threads');
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_ci// Make sure that an infinite asynchronous .on('message')/postMessage loop
81cb0ef41Sopenharmony_ci// does not lead to a stack overflow and does not starve the event loop.
91cb0ef41Sopenharmony_ci// We schedule timeouts both from before the .on('message') handler and
101cb0ef41Sopenharmony_ci// inside of it, which both should run.
111cb0ef41Sopenharmony_ci
121cb0ef41Sopenharmony_ciconst { port1, port2 } = new MessageChannel();
131cb0ef41Sopenharmony_cilet count = 0;
141cb0ef41Sopenharmony_ciport1.on('message', () => {
151cb0ef41Sopenharmony_ci  if (count === 0) {
161cb0ef41Sopenharmony_ci    setTimeout(common.mustCall(() => {
171cb0ef41Sopenharmony_ci      port1.close();
181cb0ef41Sopenharmony_ci    }), 0);
191cb0ef41Sopenharmony_ci  }
201cb0ef41Sopenharmony_ci
211cb0ef41Sopenharmony_ci  port2.postMessage(0);
221cb0ef41Sopenharmony_ci  assert(count++ < 10000, `hit ${count} loop iterations`);
231cb0ef41Sopenharmony_ci});
241cb0ef41Sopenharmony_ci
251cb0ef41Sopenharmony_ciport2.postMessage(0);
261cb0ef41Sopenharmony_ci
271cb0ef41Sopenharmony_ci// This is part of the test -- the event loop should be available and not stall
281cb0ef41Sopenharmony_ci// out due to the recursive .postMessage() calls.
291cb0ef41Sopenharmony_cisetTimeout(common.mustCall(), 0);
30