WorkerTimer

Needs to setInterval/setTimeout times working normally

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/438620/1009025/WorkerTimer.js

  1. // ==UserScript==
  2. // @license MIT
  3. // @name WorkerTimer
  4. // @version 1.2
  5. // @description Needs to setInterval/setTimeout times working normally
  6. // @author mohayonao
  7. // @match http://*/*
  8. // @match https://*/*
  9. // @grant none
  10. // @run-at document-start
  11. // @namespace https://gist.github.com/mohayonao/50547c5a51a7ca71c90d
  12. // ==/UserScript==
  13.  
  14. window.WorkerTimer = (function() {
  15. const global = window;
  16. var TIMER_WORKER_SOURCE = [
  17. "var timerIds = {}, _ = {};",
  18. "_.setInterval = function(args) {",
  19. " timerIds[args.timerId] = setInterval(function() { postMessage(args.timerId); }, args.delay);",
  20. "};",
  21. "_.clearInterval = function(args) {",
  22. " clearInterval(timerIds[args.timerId]);",
  23. "};",
  24. "_.setTimeout = function(args) {",
  25. " timerIds[args.timerId] = setTimeout(function() { postMessage(args.timerId); }, args.delay);",
  26. "};",
  27. "_.clearTimeout = function(args) {",
  28. " clearTimeout(timerIds[args.timerId]);",
  29. "};",
  30. "onmessage = function(e) { _[e.data.type](e.data) };"
  31. ].join("");
  32.  
  33. var _timerId = 0;
  34. var _callbacks = {};
  35. var _timer = new global.Worker(global.URL.createObjectURL(
  36. new global.Blob([ TIMER_WORKER_SOURCE ], { type: "text/javascript" })
  37. ));
  38.  
  39. _timer.onmessage = function(e) {
  40. if (_callbacks[e.data]) {
  41. _callbacks[e.data].callback.apply(null, _callbacks[e.data].params);
  42. }
  43. };
  44.  
  45. return {
  46. setInterval: function(callback, delay) {
  47. var params = Array.prototype.slice.call(arguments, 2);
  48.  
  49. _timerId += 1;
  50.  
  51. _timer.postMessage({ type: "setInterval", timerId: _timerId, delay: delay });
  52. _callbacks[_timerId] = { callback: callback, params: params };
  53.  
  54. return _timerId;
  55. },
  56. setTimeout: function(callback, delay) {
  57. var params = Array.prototype.slice.call(arguments, 2);
  58.  
  59. _timerId += 1;
  60.  
  61. _timer.postMessage({ type: "setTimeout", timerId: _timerId, delay: delay });
  62. _callbacks[_timerId] = { callback: callback, params: params };
  63.  
  64. return _timerId;
  65. },
  66. clearInterval: function(timerId) {
  67. _timer.postMessage({ type: "clearInterval", timerId: timerId });
  68. _callbacks[timerId] = null;
  69. },
  70. clearTimeout: function(timerId) {
  71. _timer.postMessage({ type: "clearTimeout", timerId: timerId });
  72. _callbacks[timerId] = null;
  73. }
  74. };
  75. })();