How to replace short (less than minutes) setTimeouts in event page extensions

The documentation about moving from constant background extensions to non-persistent event pages reports:

If your extension uses window.setTimeout () or window.setInterval (), switch to using the crash API instead. DOM-based timers will not run if the event page turns off.

Fair enough, but the API documentation says:

when you can set less than 1 minute after β€œnow” without warning, but actually will not trigger the alarm for at least 1 minute.

So, I have a short setTimeout in my EventPage, it takes 5 seconds, how can I make sure it is complete if I cannot use the alarm for these short times. Setting an alarm lasting 1 minute is not a solution for me.

+5
source share
1 answer

If you often need to do something like this, then wOxxOm is absolutely correct: The event page is a bad approach for your needs .

The documentation should not be misinterpreted: permanent background pages are by no means out of date. Event pages are a more efficient solution for background pages that process things irregularly and / or rarely.

Frequent timers do not fall into this category. After all, β€œexpanding” an β€œEvent” page often represents a significant loss of resource / performance rather than a constant readiness.


Now the question becomes more complicated when you just need to make this timeout as part of an infrequent rather than a regular action, when you think that long pauses between these actions can benefit from the event page model. It can happen!

Then the goal becomes busy enough for Chrome, so the Event page isn’t turned off.

Probably the easiest way is to simply call the timer a little more often, since the Event page will be saved for several seconds:

var SAFE_DELAY = 1000; // Guaranteed not to fall asleep in this interval function setBusyTimeout(callback, delay) { if(delay <= SAFE_DELAY) { setTimeout(callback, delay); } else { var start = Date.now(); // setTimeout drifts, this prevents accumulation setTimeout( function() { setBusyTimeout(callback, delay - (Date.now() - start)); }, SAFE_DELAY ); } // Can be expanded to be cancellable by maintaining a mapping // of "busy timeout IDs" to real timeoutIds } 

This is a kind of very "sparse" lively expectation that should not consume a lot of resources - again, if used infrequently.

Other souls may include maintaining an open port through chrome.runtime.connect and friends. I doubt it is more efficient with CPU than higher.

+3
source

Source: https://habr.com/ru/post/1238151/


All Articles