Erdi İzgi
Erdi İzgi

Reputation: 1322

Triggering a javascript function every two hours

I'm making a chrome extension. I need to trigger a javascript function every two hours. It is possible to do it with;

.setInterval(function(){

...

},time);

But I read about setInterval(,) and some of the developers have the opinion that 'using setInterval is bad for browser optimization'. On the other hand, I just need one trigger. I mean, I won't use it frequently. Would you advice me to continue with setInterval or is there any other way to create time based events which won't make the browser cry ?

Upvotes: 0

Views: 135

Answers (1)

Xan
Xan

Reputation: 77482

Since you're asking about a Chrome extension, you can use chrome.alarms API to do it. Do note you need the "alarms" permission.

chrome.alarms.create("my2hoursAlarm", {periodInMinutes: 120});

chrome.alarms.onAlarm.addListener(function(alarm) {
  switch(alarm.name) {
    case "my2hoursAlarm":
      // Do stuff
      break;
  }
});

The upside of using Chrome alarms is that they work well with Event pages. If your extension is not doing much and is okay with being completely unloaded between those events, chrome.alarms will wake your extension while setInterval will be wiped by the unload.

The only downside of Chrome alarms is that it can't be fired faster than once a minute. In that case you want to use setInterval anyway - and not use Event pages.

Upvotes: 4

Related Questions