1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 * @param {number} timeout
9 WebInspector.Throttler = function(timeout)
11 this._timeout = timeout;
12 this._isRunningProcess = false;
13 this._asSoonAsPossible = false;
14 /** @type {?function(!WebInspector.Throttler.FinishCallback)} */
18 WebInspector.Throttler.prototype = {
19 _processCompleted: function()
21 this._isRunningProcess = false;
23 this._innerSchedule(false);
24 this._processCompletedForTests();
27 _processCompletedForTests: function()
29 // For sniffing in tests.
32 _onTimeout: function()
34 delete this._processTimeout;
35 this._asSoonAsPossible = false;
36 this._isRunningProcess = true;
38 // Process might issue synchronous calls to this throttler.
39 var process = this._process;
41 process(this._processCompleted.bind(this));
45 * @param {function(!WebInspector.Throttler.FinishCallback)} process
46 * @param {boolean=} asSoonAsPossible
48 schedule: function(process, asSoonAsPossible)
50 // Deliberately skip previous process.
51 this._process = process;
53 // Run the first scheduled task instantly.
54 var hasScheduledTasks = !!this._processTimeout || this._isRunningProcess;
55 asSoonAsPossible = !!asSoonAsPossible || !hasScheduledTasks;
57 var forceTimerUpdate = asSoonAsPossible && !this._asSoonAsPossible;
58 this._asSoonAsPossible = this._asSoonAsPossible || asSoonAsPossible;
60 this._innerSchedule(forceTimerUpdate);
64 * @param {boolean} forceTimerUpdate
66 _innerSchedule: function(forceTimerUpdate)
68 if (this._isRunningProcess)
70 if (this._processTimeout && !forceTimerUpdate)
72 if (this._processTimeout)
73 this._clearTimeout(this._processTimeout);
75 var timeout = this._asSoonAsPossible ? 0 : this._timeout;
76 this._processTimeout = this._setTimeout(this._onTimeout.bind(this), timeout);
80 * @param {number} timeoutId
82 _clearTimeout: function(timeoutId)
84 clearTimeout(timeoutId);
88 * @param {function()} operation
89 * @param {number} timeout
92 _setTimeout: function(operation, timeout)
94 return setTimeout(operation, timeout);
98 /** @typedef {function()} */
99 WebInspector.Throttler.FinishCallback;