background.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. (function() {
  2. var _timers = {};
  3. var timers = {
  4. get: function(id) {
  5. return _timers[id] || false;
  6. },
  7. set: function(tab, interval) {
  8. var id = tab.id;
  9. (_timers[id]) && timers.remove(tab.id);
  10. _timers[id] = {
  11. tab: tab,
  12. nextRefresh: (new Date).getTime() + interval,
  13. interval: interval,
  14. timer: timers.start(id, interval)
  15. };
  16. },
  17. remove: function(id) {
  18. if(_timers[id]) {
  19. chrome.browserAction.setBadgeText({tabId: id, text: ''});
  20. clearInterval(_timers[id].timer);//不定时刷新
  21. delete _timers[id];
  22. }
  23. },
  24. start: function(id, interval) {
  25. return setInterval(function() {
  26. if(_timers[id] && (new Date).getTime() >= _timers[id].nextRefresh) {
  27. chrome.tabs.reload(id, function() {
  28. setTimeout(function() {
  29. _timers[id].nextRefresh = (new Date).getTime() + _timers[id].interval + 999;
  30. }, 1);
  31. });
  32. } else if(_timers[id]) {
  33. var timeLeft = moment(_timers[id].nextRefresh - (new Date).getTime());
  34. chrome.browserAction.setBadgeText({tabId: id, text: '' + timeLeft.format('m:ss')});
  35. } else {
  36. timers.remove(id);
  37. }
  38. }, 500);
  39. }
  40. };
  41. // Set timers on the window object so we can access it from the popdown
  42. window.timers = timers;
  43. })();