0

For testing purposes I want to detect the 'end' of a script, i.e. when no function is running anymore and no asynchronous tasks are on the queue.

In Node.js I can simply add an exit handler:

process.on('exit', () = {do_stuff();});

which will fire do_stuff() just before my node instance terminates.

For browser environments I know

window.addEventListener('beforeunload', {do_stuff();});

but that will fire do_stuff() only when I reload the site content and thus terminate the current 'instance' of my script.

How would I implement process.on('exit', fn) in ES6 for a browser?

frans
  • 8,868
  • 11
  • 58
  • 132
  • Is not possible in browser to handle some kind of `exit` event. You can just handle `beforeunload` like u said. But the question is why do you need this in browser? Could you describe your use case? Normally in testing you have to wait for element to bez present in DOM or request to be finished. – pawelbylina Jun 18 '19 at 07:00
  • 1
    The window is always ‘running’, it’s listening for user events. So there is no real process end as far as I know... Of course you can always `do_stuff()` in the final line of your own code. – Kokodoko Jun 18 '19 at 07:03
  • 1
    What do you consider the "exit" in a browser? An application can live as long as the page lives, which means `beforeunload` is the correct place. If the application you're interested in has a single (or limited) run and then finishes but the page still runs that's a different manner but it doesn't have a corresponding "end of execution" phase, since it's run inside the browser thread that still continues working. Since it's not separated, there is no concept of "it's finished". You would need to invent your own but it's dependent on the application architecture. – VLAZ Jun 18 '19 at 07:07
  • "*no asynchronous tasks are on the queue.*" - a browser continues to place DOM events (and others) in the queue as long as the page is open. Whether or not you have listeners for them is a different question. – Bergi Jun 18 '19 at 09:20

0 Answers0