Bug 882552 - Change Binder Thread's default priority to 0. r=mwu, r=jlebar
[gecko.git] / toolkit / modules / DeferredTask.jsm
blob03b53d536bde022fdfd19a4ec1640f5ebb55b929
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 this.EXPORTED_SYMBOLS = ["DeferredTask"];
7 const Cu = Components.utils;
8 const Cc = Components.classes;
9 const Ci = Components.interfaces;
11 /**
12  * A task that will run after a delay. Multiple attempts to run the same task
13  * before the delay will be coalesced
14  *
15  * Use this for instance if you write data to a file and you expect that you
16  * may have to rewrite data very soon afterwards. With |DeferredTask|, the
17  * task is delayed by a few milliseconds and, should a new change to the data
18  * occur during this period,
19  * 1/ only the final version of the data is actually written;
20  * 2/ a further grace delay is added to take into account other changes.
21  *
22  * Constructor
23  * @param aDelay The delay time in milliseconds.
24  * @param aCallback The code to execute after the delay.
25  */
26 this.DeferredTask = function DeferredTask(aCallback, aDelay) {
27   this._callback = function onCallback() {
28     this._timer = null;
29     try {
30       aCallback();
31     } catch(e) {
32       Cu.reportError(e);
33     }
34   }.bind(this);
35   this._delay = aDelay;
38 DeferredTask.prototype = {
39   /* Callback */
40   _callback: null,
41   /* Delay */
42   _delay: null,
43   /* Timer */
44   _timer: null,
46   /**
47    * Check the current task state.
48    * @returns true if pending, false otherwise.
49    */
50   get isPending() {
51     return (this._timer != null);
52   },
54   /**
55    * Start (or postpone) task.
56    */
57   start: function DeferredTask_start() {
58     if (this._timer) {
59       this._timer.cancel();
60     }
61     this._timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
62     this._timer.initWithCallback(
63       this._callback, this._delay, Ci.nsITimer.TYPE_ONE_SHOT);
64   },
66   /**
67    * Perform any postponed task immediately.
68    */
69   flush: function DeferredTask_flush() {
70     if (this._timer) {
71       this.cancel();
72       this._callback();
73     }
74   },
76   /**
77    * Cancel any pending task.
78    */
79   cancel: function DeferredTask_cancel() {
80     if (this._timer) {
81       this._timer.cancel();
82       this._timer = null;
83     }
84   }