summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/file_manager/js/async_util.js
blob: 59199eb86c8089e6c7aa0a594b145817943d5816 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/**
 * Namespace for async utility functions.
 */
var AsyncUtil = {};

/**
 * Creates a class for executing several asynchronous closures in a fifo queue.
 * Added tasks will be executed sequentially in order they were added.
 *
 * @constructor
 */
AsyncUtil.Queue = function() {
  this.running_ = false;
  this.closures_ = [];
};

/**
 * Enqueues a closure to be executed.
 * @param {function(function())} closure Closure with a completion callback to
 *     be executed.
 */
AsyncUtil.Queue.prototype.run = function(closure) {
  this.closures_.push(closure);
  if (!this.running_)
    this.continue_();
};

/**
 * Serves the next closure from the queue.
 * @private
 */
AsyncUtil.Queue.prototype.continue_ = function() {
  if (!this.closures_.length) {
    this.running_ = false;
    return;
  }

  // Run the next closure.
  this.running_ = true;
  var closure = this.closures_.shift();
  closure(this.continue_.bind(this));
};

/**
 * Creates a class for executing several asynchronous closures in a group in
 * a dependency order.
 *
 * @constructor
 */
AsyncUtil.Group = function() {
  this.addedTasks_ = {};
  this.pendingTasks_ = {};
  this.finishedTasks_ = {};
  this.completionCallbacks_ = [];
};

/**
 * Enqueues a closure to be executed after dependencies are completed.
 *
 * @param {function(function())} closure Closure with a completion callback to
 *     be executed.
 * @param {Array.<string>=} opt_dependencies Array of dependencies. If no
 *     dependencies, then the the closure will be executed immediately.
 * @param {string=} opt_name Task identifier. Specify to use in dependencies.
 */
AsyncUtil.Group.prototype.add = function(closure, opt_dependencies, opt_name) {
  var length = Object.keys(this.addedTasks_).length;
  var name = opt_name || ('(unnamed#' + (length + 1) + ')');

  var task = {
    closure: closure,
    dependencies: opt_dependencies || [],
    name: name
  };

  this.addedTasks_[name] = task;
  this.pendingTasks_[name] = task;
};

/**
 * Runs the enqueued closured in order of dependencies.
 *
 * @param {function()=} opt_onCompletion Completion callback.
 */
AsyncUtil.Group.prototype.run = function(opt_onCompletion) {
  if (opt_onCompletion)
    this.completionCallbacks_.push(opt_onCompletion);
  this.continue_();
};

/**
 * Runs enqueued pending tasks whose dependencies are completed.
 * @private
 */
AsyncUtil.Group.prototype.continue_ = function() {
  // If all of the added tasks have finished, then call completion callbacks.
  if (Object.keys(this.addedTasks_).length ==
      Object.keys(this.finishedTasks_).length) {
    for (var index = 0; index < this.completionCallbacks_.length; index++) {
      var callback = this.completionCallbacks_[index];
      callback();
    }
    this.completionCallbacks_ = [];
    return;
  }

  for (var name in this.pendingTasks_) {
    var task = this.pendingTasks_[name];
    var dependencyMissing = false;
    for (var index = 0; index < task.dependencies.length; index++) {
      var dependency = task.dependencies[index];
      // Check if the dependency has finished.
      if (!this.finishedTasks_[dependency])
        dependencyMissing = true;
    }
    // All dependences finished, therefore start the task.
    if (!dependencyMissing) {
      delete this.pendingTasks_[task.name];
      task.closure(this.finish_.bind(this, task));
    }
  }
};

/**
 * Finishes the passed task and continues executing enqueued closures.
 *
 * @param {Object} task Task object.
 * @private
 */
AsyncUtil.Group.prototype.finish_ = function(task) {
  this.finishedTasks_[task.name] = task;
  this.continue_();
};

/**
 * Aggregates consecutive calls and executes the closure only once instead of
 * several times. The first call is always called immediately, and the next
 * consecutive ones are aggregated and the closure is called only once once
 * |delay| amount of time passes after the last call to run().
 *
 * @param {function()} closure Closure to be aggregated.
 * @param {number=} opt_delay Minimum aggregation time in milliseconds. Default
 *     is 50 milliseconds.
 * @constructor
 */
AsyncUtil.Aggregation = function(closure, opt_delay) {
  /**
   * @type {number}
   * @private
   */
  this.delay_ = opt_delay || 50;

  /**
   * @type {function()}
   * @private
   */
  this.closure_ = closure;

  /**
   * @type {number?}
   * @private
   */
  this.scheduledRunsTimer_ = null;

  /**
   * @type {number}
   * @private
   */
  this.lastRunTime_ = 0;
};

/**
 * Runs a closure. Skips consecutive calls. The first call is called
 * immediately.
 */
AsyncUtil.Aggregation.prototype.run = function() {
  // If recently called, then schedule the consecutive call with a delay.
  if (Date.now() - this.lastRunTime_ < this.delay_) {
    this.cancelScheduledRuns_();
    this.scheduledRunsTimer_ = setTimeout(this.runImmediately_.bind(this),
                                          this.delay_ + 1);
    this.lastRunTime_ = Date.now();
    return;
  }

  // Otherwise, run immediately.
  this.runImmediately_();
};

/**
 * Calls the schedule immediately and cancels any scheduled calls.
 * @private
 */
AsyncUtil.Aggregation.prototype.runImmediately_ = function() {
  this.cancelScheduledRuns_();
  this.closure_();
  this.lastRunTime_ = Date.now();
};

/**
 * Cancels all scheduled runs (if any).
 * @private
 */
AsyncUtil.Aggregation.prototype.cancelScheduledRuns_ = function() {
  if (this.scheduledRunsTimer_) {
    clearTimeout(this.scheduledRunsTimer_);
    this.scheduledRunsTimer_ = null;
  }
};