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.
6 * @fileoverview Provides a watchdog around a collection of callback functions.
11 * Creates a watchdog around a collection of callback functions,
12 * ensuring at least one of them is called before the timeout expires.
13 * If a timeout function is provided, calls the timeout function upon timeout
14 * expiration if none of the callback functions has been called.
15 * @param {number} timeoutValueSeconds Timeout value, in seconds.
16 * @param {function()=} opt_timeoutCb Callback function to call on timeout.
18 * @implements {Closeable}
20 function WatchdogRequestHandler(timeoutValueSeconds, opt_timeoutCb) {
21 /** @private {number} */
22 this.timeoutValueSeconds_ = timeoutValueSeconds;
23 /** @private {function()|undefined} */
24 this.timeoutCb_ = opt_timeoutCb;
25 /** @private {boolean} */
26 this.calledBack_ = false;
27 /** @private {Countdown} */
28 this.timer_ = FACTORY_REGISTRY.getCountdownFactory().createTimer(
29 this.timeoutValueSeconds_ * 1000, this.timeout_.bind(this));
30 /** @private {Closeable|undefined} */
31 this.closeable_ = undefined;
32 /** @private {boolean} */
37 * Wraps a callback function, such that the fact that the callback function
38 * was or was not called gets tracked by this watchdog object.
39 * @param {function(...?)} cb The callback function to wrap.
40 * @return {function(...?)} A wrapped callback function.
42 WatchdogRequestHandler.prototype.wrapCallback = function(cb) {
43 return this.wrappedCallback_.bind(this, cb);
46 /** Closes this watchdog. */
47 WatchdogRequestHandler.prototype.close = function() {
49 this.timer_.clearTimeout();
50 if (this.closeable_) {
51 this.closeable_.close();
52 this.closeable_ = undefined;
57 * Sets this watchdog's closeable.
58 * @param {!Closeable} closeable The closeable.
60 WatchdogRequestHandler.prototype.setCloseable = function(closeable) {
61 this.closeable_ = closeable;
65 * Called back when the watchdog expires.
68 WatchdogRequestHandler.prototype.timeout_ = function() {
69 if (!this.calledBack_ && !this.closed_) {
70 var logMsg = 'Not called back within ' + this.timeoutValueSeconds_ +
72 if (this.timeoutCb_) {
73 logMsg += ', calling default callback';
74 console.warn(UTIL_fmt(logMsg));
77 console.warn(UTIL_fmt(logMsg));
83 * Wrapped callback function.
84 * @param {function(...?)} cb The callback function to call.
85 * @param {...?} var_args The callback function's arguments.
88 WatchdogRequestHandler.prototype.wrappedCallback_ = function(cb, var_args) {
90 this.calledBack_ = true;
91 this.timer_.clearTimeout();
92 var originalArgs = Array.prototype.slice.call(arguments, 1);
93 cb.apply(null, originalArgs);