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;
12 * A task that will run after a delay. Multiple attempts to run the same task
13 * before the delay will be coalesced
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.
23 * @param aDelay The delay time in milliseconds.
24 * @param aCallback The code to execute after the delay.
26 this.DeferredTask = function DeferredTask(aCallback, aDelay) {
27 this._callback = function onCallback() {
38 DeferredTask.prototype = {
47 * Check the current task state.
48 * @returns true if pending, false otherwise.
51 return (this._timer != null);
55 * Start (or postpone) task.
57 start: function DeferredTask_start() {
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);
67 * Perform any postponed task immediately.
69 flush: function DeferredTask_flush() {
77 * Cancel any pending task.
79 cancel: function DeferredTask_cancel() {