PageRenderTime 50ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/src/time/Timer.js

https://gitlab.com/lobsterhands/phaser
JavaScript | 608 lines | 257 code | 123 blank | 228 comment | 39 complexity | 760305f57a45a1fe1aae6d1efcc8eb1b MD5 | raw file
  1. /**
  2. * @author Richard Davey <rich@photonstorm.com>
  3. * @copyright 2014 Photon Storm Ltd.
  4. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  5. */
  6. /**
  7. * A Timer is a way to create small re-usable or disposable objects that do nothing but wait for a specific moment in time, and then dispatch an event.
  8. * You can add as many events to a Timer as you like, each with their own delays. A Timer uses milliseconds as its unit of time. There are 1000 ms in 1 second.
  9. * So if you want to fire an event every quarter of a second you'd need to set the delay to 250.
  10. *
  11. * @class Phaser.Timer
  12. * @classdesc A Timer is a way to create small re-usable or disposable objects that do nothing but wait for a specific moment in time, and then dispatch an event.
  13. * @constructor
  14. * @param {Phaser.Game} game A reference to the currently running game.
  15. * @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events).
  16. */
  17. Phaser.Timer = function (game, autoDestroy) {
  18. if (typeof autoDestroy === 'undefined') { autoDestroy = true; }
  19. /**
  20. * @property {Phaser.Game} game - Local reference to game.
  21. */
  22. this.game = game;
  23. /**
  24. * @property {boolean} running - True if the Timer is actively running. Do not switch this boolean, if you wish to pause the timer then use Timer.pause() instead.
  25. * @default
  26. */
  27. this.running = false;
  28. /**
  29. * @property {boolean} autoDestroy - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events).
  30. */
  31. this.autoDestroy = autoDestroy;
  32. /**
  33. * @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending.
  34. * @readonly
  35. * @default
  36. */
  37. this.expired = false;
  38. /**
  39. * @property {array<Phaser.TimerEvent>} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it.
  40. */
  41. this.events = [];
  42. /**
  43. * @property {Phaser.Signal} onComplete - This signal will be dispatched when this Timer has completed, meaning there are no more events in the queue.
  44. */
  45. this.onComplete = new Phaser.Signal();
  46. /**
  47. * @property {number} nextTick - The time the next tick will occur.
  48. * @readonly
  49. * @protected
  50. */
  51. this.nextTick = 0;
  52. /**
  53. * @property {boolean} paused - The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing.
  54. * @readonly
  55. * @default
  56. */
  57. this.paused = false;
  58. /**
  59. * @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss?
  60. * @private
  61. */
  62. this._codePaused = false;
  63. /**
  64. * @property {number} _started - The time at which this Timer instance started running.
  65. * @private
  66. * @default
  67. */
  68. this._started = 0;
  69. /**
  70. * @property {number} _pauseStarted - The time the game started being paused.
  71. * @private
  72. */
  73. this._pauseStarted = 0;
  74. /**
  75. * @property {number} _pauseTotal - Total paused time.
  76. * @private
  77. */
  78. this._pauseTotal = 0;
  79. /**
  80. * @property {number} _now - The current start-time adjusted time.
  81. * @private
  82. */
  83. this._now = 0;
  84. /**
  85. * @property {number} _len - Temp. array length variable.
  86. * @private
  87. */
  88. this._len = 0;
  89. /**
  90. * @property {number} _i - Temp. array counter variable.
  91. * @private
  92. */
  93. this._i = 0;
  94. };
  95. /**
  96. * @constant
  97. * @type {number}
  98. */
  99. Phaser.Timer.MINUTE = 60000;
  100. /**
  101. * @constant
  102. * @type {number}
  103. */
  104. Phaser.Timer.SECOND = 1000;
  105. /**
  106. * @constant
  107. * @type {number}
  108. */
  109. Phaser.Timer.HALF = 500;
  110. /**
  111. * @constant
  112. * @type {number}
  113. */
  114. Phaser.Timer.QUARTER = 250;
  115. Phaser.Timer.prototype = {
  116. /**
  117. * Creates a new TimerEvent on this Timer. Use the methods add, repeat or loop instead of this.
  118. * @method Phaser.Timer#create
  119. * @private
  120. * @param {number} delay - The number of milliseconds that should elapse before the Timer will call the given callback.
  121. * @param {boolean} loop - Should the event loop or not?
  122. * @param {number} repeatCount - The number of times the event will repeat.
  123. * @param {function} callback - The callback that will be called when the Timer event occurs.
  124. * @param {object} callbackContext - The context in which the callback will be called.
  125. * @param {array} arguments - The values to be sent to your callback function when it is called.
  126. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  127. */
  128. create: function (delay, loop, repeatCount, callback, callbackContext, args) {
  129. var tick = delay;
  130. if (this._now === 0)
  131. {
  132. tick += this.game.time.now;
  133. }
  134. else
  135. {
  136. tick += this._now;
  137. }
  138. var event = new Phaser.TimerEvent(this, delay, tick, repeatCount, loop, callback, callbackContext, args);
  139. this.events.push(event);
  140. this.order();
  141. this.expired = false;
  142. return event;
  143. },
  144. /**
  145. * Adds a new Event to this Timer. The event will fire after the given amount of 'delay' in milliseconds has passed, once the Timer has started running.
  146. * Call Timer.start() once you have added all of the Events you require for this Timer. The delay is in relation to when the Timer starts, not the time it was added.
  147. * If the Timer is already running the delay will be calculated based on the timers current time.
  148. * @method Phaser.Timer#add
  149. * @param {number} delay - The number of milliseconds that should elapse before the Timer will call the given callback.
  150. * @param {function} callback - The callback that will be called when the Timer event occurs.
  151. * @param {object} callbackContext - The context in which the callback will be called.
  152. * @param {...*} arguments - The values to be sent to your callback function when it is called.
  153. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  154. */
  155. add: function (delay, callback, callbackContext) {
  156. return this.create(delay, false, 0, callback, callbackContext, Array.prototype.splice.call(arguments, 3));
  157. },
  158. /**
  159. * Adds a new Event to this Timer that will repeat for the given number of iterations.
  160. * The event will fire after the given amount of 'delay' milliseconds has passed once the Timer has started running.
  161. * Call Timer.start() once you have added all of the Events you require for this Timer. The delay is in relation to when the Timer starts, not the time it was added.
  162. * If the Timer is already running the delay will be calculated based on the timers current time.
  163. * @method Phaser.Timer#repeat
  164. * @param {number} delay - The number of milliseconds that should elapse before the Timer will call the given callback.
  165. * @param {number} repeatCount - The number of times the event will repeat.
  166. * @param {function} callback - The callback that will be called when the Timer event occurs.
  167. * @param {object} callbackContext - The context in which the callback will be called.
  168. * @param {...*} arguments - The values to be sent to your callback function when it is called.
  169. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  170. */
  171. repeat: function (delay, repeatCount, callback, callbackContext) {
  172. return this.create(delay, false, repeatCount, callback, callbackContext, Array.prototype.splice.call(arguments, 4));
  173. },
  174. /**
  175. * Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped.
  176. * The event will fire after the given amount of 'delay' milliseconds has passed once the Timer has started running.
  177. * Call Timer.start() once you have added all of the Events you require for this Timer. The delay is in relation to when the Timer starts, not the time it was added.
  178. * If the Timer is already running the delay will be calculated based on the timers current time.
  179. * @method Phaser.Timer#loop
  180. * @param {number} delay - The number of milliseconds that should elapse before the Timer will call the given callback.
  181. * @param {function} callback - The callback that will be called when the Timer event occurs.
  182. * @param {object} callbackContext - The context in which the callback will be called.
  183. * @param {...*} arguments - The values to be sent to your callback function when it is called.
  184. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  185. */
  186. loop: function (delay, callback, callbackContext) {
  187. return this.create(delay, true, 0, callback, callbackContext, Array.prototype.splice.call(arguments, 3));
  188. },
  189. /**
  190. * Starts this Timer running.
  191. * @method Phaser.Timer#start
  192. * @param {number} [delay=0] - The number of milliseconds that should elapse before the Timer will start.
  193. */
  194. start: function (delay) {
  195. if (this.running)
  196. {
  197. return;
  198. }
  199. this._started = this.game.time.now + (delay || 0);
  200. this.running = true;
  201. for (var i = 0; i < this.events.length; i++)
  202. {
  203. this.events[i].tick = this.events[i].delay + this._started;
  204. }
  205. },
  206. /**
  207. * Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true.
  208. * @method Phaser.Timer#stop
  209. * @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain.
  210. */
  211. stop: function (clearEvents) {
  212. this.running = false;
  213. if (typeof clearEvents === 'undefined') { clearEvents = true; }
  214. if (clearEvents)
  215. {
  216. this.events.length = 0;
  217. }
  218. },
  219. /**
  220. * Removes a pending TimerEvent from the queue.
  221. * @param {Phaser.TimerEvent} event - The event to remove from the queue.
  222. * @method Phaser.Timer#remove
  223. */
  224. remove: function (event) {
  225. for (var i = 0; i < this.events.length; i++)
  226. {
  227. if (this.events[i] === event)
  228. {
  229. this.events[i].pendingDelete = true;
  230. return true;
  231. }
  232. }
  233. return false;
  234. },
  235. /**
  236. * Orders the events on this Timer so they are in tick order. This is called automatically when new events are created.
  237. * @method Phaser.Timer#order
  238. */
  239. order: function () {
  240. if (this.events.length > 0)
  241. {
  242. // Sort the events so the one with the lowest tick is first
  243. this.events.sort(this.sortHandler);
  244. this.nextTick = this.events[0].tick;
  245. }
  246. },
  247. /**
  248. * Sort handler used by Phaser.Timer.order.
  249. * @method Phaser.Timer#sortHandler
  250. * @protected
  251. */
  252. sortHandler: function (a, b) {
  253. if (a.tick < b.tick)
  254. {
  255. return -1;
  256. }
  257. else if (a.tick > b.tick)
  258. {
  259. return 1;
  260. }
  261. return 0;
  262. },
  263. /**
  264. * The main Timer update event, called automatically by the Game clock.
  265. * @method Phaser.Timer#update
  266. * @protected
  267. * @param {number} time - The time from the core game clock.
  268. * @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed.
  269. */
  270. update: function (time) {
  271. if (this.paused)
  272. {
  273. return true;
  274. }
  275. this._now = time;
  276. this._len = this.events.length;
  277. this._i = 0;
  278. while (this._i < this._len)
  279. {
  280. if (this.events[this._i].pendingDelete)
  281. {
  282. this.events.splice(this._i, 1);
  283. this._len--;
  284. }
  285. this._i++;
  286. }
  287. this._len = this.events.length;
  288. if (this.running && this._now >= this.nextTick && this._len > 0)
  289. {
  290. this._i = 0;
  291. while (this._i < this._len && this.running)
  292. {
  293. if (this._now >= this.events[this._i].tick)
  294. {
  295. var diff = this._now - this.events[this._i].tick;
  296. var newTick = (this._now + this.events[this._i].delay) - diff;
  297. if (newTick < 0)
  298. {
  299. newTick = this._now + this.events[this._i].delay;
  300. }
  301. if (this.events[this._i].loop === true)
  302. {
  303. this.events[this._i].tick = newTick;
  304. this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
  305. }
  306. else if (this.events[this._i].repeatCount > 0)
  307. {
  308. this.events[this._i].repeatCount--;
  309. this.events[this._i].tick = newTick;
  310. this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
  311. }
  312. else
  313. {
  314. this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
  315. this.events.splice(this._i, 1);
  316. this._len--;
  317. }
  318. this._i++;
  319. }
  320. else
  321. {
  322. break;
  323. }
  324. }
  325. // Are there any events left?
  326. if (this.events.length > 0)
  327. {
  328. this.order();
  329. }
  330. else
  331. {
  332. this.expired = true;
  333. this.onComplete.dispatch(this);
  334. }
  335. }
  336. if (this.expired && this.autoDestroy)
  337. {
  338. return false;
  339. }
  340. else
  341. {
  342. return true;
  343. }
  344. },
  345. /**
  346. * Pauses the Timer and all events in the queue.
  347. * @method Phaser.Timer#pause
  348. */
  349. pause: function () {
  350. if (this.running && !this.expired)
  351. {
  352. this._pauseStarted = this.game.time.now;
  353. this.paused = true;
  354. this._codePaused = true;
  355. }
  356. },
  357. /**
  358. * This is called by the core Game loop. Do not call it directly, instead use Timer.pause.
  359. * @method Phaser.Timer#_pause
  360. * @private
  361. */
  362. _pause: function () {
  363. if (this.running && !this.expired)
  364. {
  365. this._pauseStarted = this.game.time.now;
  366. this.paused = true;
  367. }
  368. },
  369. /**
  370. * Resumes the Timer and updates all pending events.
  371. * @method Phaser.Timer#resume
  372. */
  373. resume: function () {
  374. if (this.running && !this.expired)
  375. {
  376. var pauseDuration = this.game.time.now - this._pauseStarted;
  377. this._pauseTotal += pauseDuration;
  378. for (var i = 0; i < this.events.length; i++)
  379. {
  380. this.events[i].tick += pauseDuration;
  381. }
  382. this.nextTick += pauseDuration;
  383. this.paused = false;
  384. this._codePaused = false;
  385. }
  386. },
  387. /**
  388. * This is called by the core Game loop. Do not call it directly, instead use Timer.pause.
  389. * @method Phaser.Timer#_resume
  390. * @private
  391. */
  392. _resume: function () {
  393. if (this._codePaused)
  394. {
  395. return;
  396. }
  397. else
  398. {
  399. this.resume();
  400. }
  401. },
  402. /**
  403. * Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running.
  404. * The onComplete callbacks won't be called.
  405. *
  406. * @method Phaser.Timer#removeAll
  407. */
  408. removeAll: function () {
  409. this.onComplete.removeAll();
  410. this.events.length = 0;
  411. this._len = 0;
  412. this._i = 0;
  413. },
  414. /**
  415. * Destroys this Timer. Any pending Events are not dispatched.
  416. * The onComplete callbacks won't be called.
  417. *
  418. * @method Phaser.Timer#destroy
  419. */
  420. destroy: function () {
  421. this.onComplete.removeAll();
  422. this.running = false;
  423. this.events = [];
  424. this._len = 0;
  425. this._i = 0;
  426. }
  427. };
  428. /**
  429. * @name Phaser.Timer#next
  430. * @property {number} next - The time at which the next event will occur.
  431. * @readonly
  432. */
  433. Object.defineProperty(Phaser.Timer.prototype, "next", {
  434. get: function () {
  435. return this.nextTick;
  436. }
  437. });
  438. /**
  439. * @name Phaser.Timer#duration
  440. * @property {number} duration - The duration in ms remaining until the next event will occur.
  441. * @readonly
  442. */
  443. Object.defineProperty(Phaser.Timer.prototype, "duration", {
  444. get: function () {
  445. if (this.running && this.nextTick > this._now)
  446. {
  447. return this.nextTick - this._now;
  448. }
  449. else
  450. {
  451. return 0;
  452. }
  453. }
  454. });
  455. /**
  456. * @name Phaser.Timer#length
  457. * @property {number} length - The number of pending events in the queue.
  458. * @readonly
  459. */
  460. Object.defineProperty(Phaser.Timer.prototype, "length", {
  461. get: function () {
  462. return this.events.length;
  463. }
  464. });
  465. /**
  466. * @name Phaser.Timer#ms
  467. * @property {number} ms - The duration in milliseconds that this Timer has been running for.
  468. * @readonly
  469. */
  470. Object.defineProperty(Phaser.Timer.prototype, "ms", {
  471. get: function () {
  472. return this._now - this._started - this._pauseTotal;
  473. }
  474. });
  475. /**
  476. * @name Phaser.Timer#seconds
  477. * @property {number} seconds - The duration in seconds that this Timer has been running for.
  478. * @readonly
  479. */
  480. Object.defineProperty(Phaser.Timer.prototype, "seconds", {
  481. get: function () {
  482. return this.ms * 0.001;
  483. }
  484. });
  485. Phaser.Timer.prototype.constructor = Phaser.Timer;