Call a function every minute from a service worker

2019-09-20 07:23发布

问题:

I'm working on a Progressive Web App (PWA) with offline support and I need to call a function in the app every minute from the service worker. (to send a web API based push notification if the user is offline)

What is the best way to do this?

回答1:

to call the function every minute use setInterval():

function myFunction(){
	console.log('called evry minute')
}

setInterval(myFunction, 1000);

But you can listen for online and offline events to send the notifications accordingly , see compatibility of NavigatorOnLine , as it won't work in Opera

window.addEventListener('online',  functionWhenOnline);
window.addEventListener('offline', functionWhenOffline);