Run pn.state.on_session_destroyed() immediately after closing browser tab

I have an app which execute a time consuming calculation. When the browser tab is closed, I’d like the process stop immediately and run on_session_destroyed(). However, it appears that the app run the calculation until it finishes or crashes. Is there a way to do it?

In the following example, I replace the calculation part by sleep.

import datetime
import time

import panel as pn

pn.extension()


def destroyed(session_context):
    print(f"{datetime.datetime.now()}: Session destroyed!")


pn.state.on_session_destroyed(destroyed)

button = pn.widgets.Button(name="Click me!")


def click_to_sleep(clicked):
    if clicked:
        print(f"{datetime.datetime.now()}: sleep start")
        time.sleep(60)
        print(f"{datetime.datetime.now()}: sleep end")


pn.bind(click_to_sleep, button, watch=True)

app = pn.Column(button)
app.servable()

I’m using Panel 1.4.4 with Python 3.11.8.

You’d probably need to incorporate async like asyncio.create_task and cancel task.

Thanks! It’s new to me, but I’ll check what can be done with it.