timers.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // License https://jryans.mit-license.org/
  2. import {setImmediate, clearImmediate} from './setimmediate';
  3. export {setImmediate, clearImmediate};
  4. // DOM APIs, for completeness
  5. var apply = Function.prototype.apply;
  6. export function clearInterval(timeout) {
  7. if (typeof timeout === 'number' && typeof global.clearInterval === 'function') {
  8. global.clearInterval(timeout);
  9. } else {
  10. clearFn(timeout)
  11. }
  12. }
  13. export function clearTimeout(timeout) {
  14. if (typeof timeout === 'number' && typeof global.clearTimeout === 'function') {
  15. global.clearTimeout(timeout);
  16. } else {
  17. clearFn(timeout)
  18. }
  19. }
  20. function clearFn(timeout) {
  21. if (timeout && typeof timeout.close === 'function') {
  22. timeout.close();
  23. }
  24. }
  25. export function setTimeout() {
  26. return new Timeout(apply.call(global.setTimeout, window, arguments), clearTimeout);
  27. }
  28. export function setInterval() {
  29. return new Timeout(apply.call(global.setInterval, window, arguments), clearInterval);
  30. }
  31. function Timeout(id) {
  32. this._id = id;
  33. }
  34. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  35. Timeout.prototype.close = function() {
  36. clearFn(this._id);
  37. }
  38. // Does not start the time, just sets up the members needed.
  39. export function enroll(item, msecs) {
  40. clearTimeout(item._idleTimeoutId);
  41. item._idleTimeout = msecs;
  42. }
  43. export function unenroll(item) {
  44. clearTimeout(item._idleTimeoutId);
  45. item._idleTimeout = -1;
  46. }
  47. export var _unrefActive = active;
  48. export function active(item) {
  49. clearTimeout(item._idleTimeoutId);
  50. var msecs = item._idleTimeout;
  51. if (msecs >= 0) {
  52. item._idleTimeoutId = setTimeout(function onTimeout() {
  53. if (item._onTimeout)
  54. item._onTimeout();
  55. }, msecs);
  56. }
  57. }
  58. export default {
  59. setImmediate: setImmediate,
  60. clearImmediate: clearImmediate,
  61. setTimeout: setTimeout,
  62. clearTimeout: clearTimeout,
  63. setInterval: setInterval,
  64. clearInterval: clearInterval,
  65. active: active,
  66. unenroll: unenroll,
  67. _unrefActive: _unrefActive,
  68. enroll: enroll
  69. };