Enlish | 中文版
A javascript Timer which works well in inactive tab.
Most of the modern browsers throttled setTimeout/setInterval to more than 1000ms if the page's inactive. In most of the cases, it saves CPU loads while the tabs are inactive, which's a good thing. But in some extreme cases (like sending heart beating packet), it requires the page to have a stable timer.
I've tried to search if there's any methods to prevent browsers throttling timers, but so far it seems like WebWorker could be the only solution to prevent throttling.
<script src="path/to/your/index.web.min.js">
import Timer from 'Timer';
// Instanize the Timer.
let T = new Timer();
// calibrate, reduce the time offset of asynchornaze work.
T.calibrate();
// The same API as window.setTimeout/window.setInterval
T.setTimeout(fn, delay, ...params);
T.setInterval(fn, delay, ...params);
T.setImmediate(fn, ...params);
T.clearTimeout(timeoutID);
T.clearInterval(intervalID);
T.clearImmediate(immediateID);
// These are newly added
T.hasTimer(timerID)
T.clearAll()
- add test cases.
MIT License
Copyright (c) 2018 Jacky Wang