Index: chrome/browser/resources/md_bookmarks/timer_proxy.js |
diff --git a/chrome/browser/resources/md_bookmarks/timer_proxy.js b/chrome/browser/resources/md_bookmarks/timer_proxy.js |
index de96c7fdb4ec7aa2b5bfe9c2329ccaff095de13f..091023fecb5ccca8abc8d783ac6e012ac706e948 100644 |
--- a/chrome/browser/resources/md_bookmarks/timer_proxy.js |
+++ b/chrome/browser/resources/md_bookmarks/timer_proxy.js |
@@ -13,7 +13,7 @@ cr.define('bookmarks', function() { |
TimerProxy.prototype = { |
/** |
- * @param {Function|string} fn |
+ * @param {function()|string} fn |
* @param {number=} delay |
* @return {number} |
*/ |
@@ -27,7 +27,63 @@ cr.define('bookmarks', function() { |
}, |
}; |
+ /** |
+ * A one-shot debouncer which fires the given callback after a delay. The |
+ * delay can be refreshed by calling resetTimer. Resetting with no delay moves |
+ * the callback to the end of the task queue. |
+ * @param {!function()} callback |
+ * @constructor |
+ */ |
+ function Debouncer(callback) { |
+ /** @private {!function()} */ |
+ this.callback_ = callback; |
+ /** @private {!bookmarks.TimerProxy} */ |
+ this.timerProxy_ = new TimerProxy(); |
+ /** @private {?number} */ |
+ this.timer_ = null; |
+ /** @private {!function()} */ |
+ this.boundTimerCallback_ = this.timerCallback_.bind(this); |
+ /** @private {boolean} */ |
+ this.isDone_ = false; |
+ /** @private {!PromiseResolver} */ |
+ this.promiseResolver_ = new PromiseResolver(); |
+ } |
+ |
+ Debouncer.prototype = { |
+ /** |
+ * @param {number=} delay |
+ */ |
+ resetTimeout: function(delay) { |
+ if (this.timer_) |
+ this.timerProxy_.clearTimeout(this.timer_); |
+ this.timer_ = |
+ this.timerProxy_.setTimeout(this.boundTimerCallback_, delay); |
+ }, |
+ |
+ /** |
+ * @return {boolean} True if the Debouncer has finished processing. |
+ */ |
+ done: function() { |
+ return this.isDone_; |
+ }, |
+ |
+ /** |
+ * @return {Promise} Promise which resolves immediately after the callback. |
+ */ |
+ get promise() { |
+ return this.promiseResolver_.promise; |
+ }, |
+ |
+ /** @private */ |
+ timerCallback_: function() { |
+ this.isDone_ = true; |
+ this.callback_.call(); |
+ this.promiseResolver_.resolve(); |
+ }, |
+ }; |
+ |
return { |
+ Debouncer: Debouncer, |
TimerProxy: TimerProxy, |
}; |
}); |