I want to create a timer, which starts the countdown on notification click.
My sample works well as long as the break length is less than one minute. When the break length is longer than a minute, service worker stops working.
index.html
<!DOCTYPE html>
<html>
<body>
<button onclick="notify();">notify</button>
</body>
<script>
function notify() {
const items = ["First", "End of the break", "Second"];
const options = { data: items };
if ('serviceWorker' in navigator) {
Notification.requestPermission()
.then(() => navigator.serviceWorker.register('sw.js'))
.then(() => navigator.serviceWorker.ready
.then((s) => {
s.showNotification('Click to begin', options);
}))
.catch(e => console.log(e.message));
}
}
</script>
</html>
sw.js
let data = [];
let num = 0;
self.onnotificationclick = (event) => {
event.notification.close();
if (event.notification.data) {
({ data } = event.notification);
}
if (num < data.length) {
setTimeout(() => {
self.registration.showNotification(data[num]);
num += 1;
}, num % 2 === 0 ? 1 : 3000);
}
};
I am aware that there should be no setTimeout in sw.js, but it's the closest to the point I want to achieve.
Is there a way to build a timer that starts counting down when you click a notification and notifies you about the end of countdown?