Interval Looper

非同步数组枚举回调

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.gf.qytechs.cn/scripts/3588/10916/Interval%20Looper.js

  1. // Interval Looper by Jixun:
  2. // https://gist.github.com/JixunMoe/c77bb3936a68997fce22
  3.  
  4. var IntervalLoop = function (arrData, looper, delay) {
  5. if (!(this instanceof IntervalLoop))
  6. return new IntervalLoop (arrData, looper, delay);
  7. /**
  8. * Status
  9. * @type Number
  10. * 0: 循环未开始
  11. * 1: 正在循环
  12. * 2: 循环结束
  13. */
  14. this.status = 0;
  15. this.next = this._next.bind (this);
  16. this.index = 0;
  17. this.setDelay (delay || 50);
  18. this.data = (arrData instanceof Array) ? arrData : [];
  19. this.setLooper (looper);
  20. };
  21. IntervalLoop.prototype = {
  22. _getDelay: function () {
  23. if (!this.delay)
  24. return 50;
  25. if (this.delay.apply)
  26. return this.delay();
  27. return this.delay;
  28. },
  29. _next: function () {
  30. // 状态改为 进行中
  31. this.status = 1;
  32. if (this.index < this.data.length) {
  33. setTimeout (this.looper.bind(this, this.data[this.index]), this.delay);
  34. this.index ++;
  35. if (this.onProgress && this.onProgress.apply) {
  36. try {
  37. this.onProgress (this.index, this.data.length);
  38. } catch (e) {
  39. console.error ('Error while callback to `onProgress`');
  40. console.error (e);
  41. }
  42. }
  43. } else {
  44. this.status = 2;
  45. if (this.onComplete && this.onComplete.apply) {
  46. try {
  47. this.onComplete (this.data.length);
  48. } catch (e) {
  49. console.error ('Error while callback to `onComplete`');
  50. console.error (e);
  51. }
  52. }
  53. }
  54. },
  55. cleanup: function () {
  56. if (this.status == 2) {
  57. // 已经用过的数据就清掉。
  58. this.data.splice(0, this.index);
  59. this.index = 0;
  60. this.status = 0;
  61. }
  62. return this;
  63. },
  64. add: function () {
  65. if (arguments.length > 0) {
  66. // 将所有参数作为数据推入 this.data
  67. for (var i = 0; i<arguments.length; i++)
  68. this.data.push (arguments[i]);
  69. // 整个组已经完结,清理后自动继续
  70. if (this.status == 2)
  71. this.cleanup().next();
  72. }
  73. // 连锁
  74. return this;
  75. },
  76. setDelay: function (newDelay) {
  77. if (newDelay) this.delay = parseInt (newDelay);
  78. return this;
  79. },
  80. setLooper: function (fooCallback) {
  81. if (fooCallback && fooCallback.apply)
  82. this.looper = fooCallback.bind(this, this.next);
  83. return this;
  84. },
  85. loop: function () {
  86. if (this.status == 0)
  87. // 尚未启动, 从头开始
  88. this.next ();
  89. return this;
  90. }
  91. };

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址