How catch open close event of Chrome browser tab?

I have a project like a web base chat application. It contains one page. The JavaScript code is listening to new message from the server through a fetch statement in a setinterval, then displaying on page. What I need is a way to catch the open and close event of the browser tab then I can set interval listening on and of.
Thanks in advance.