3 var debug = require('debug-proxy')('app:conditional-debounce');
6 * This is a special type of debounce function in which the
7 * all the conditions have to be met before the debounce function
8 * will fire. If any of the conditions become unmet, the timer
11 * It is used in `reload-on-update` to ensure that the user is
12 * eyeballs off, online, etc before reloading the browser.
14 * Remember: Even when all the conditions are met, they need to remain met
15 * until the timeout has expired.
17 function ConditionalDebouncer(conditions, timeout, fn) {
18 this.conditions = conditions;
19 this.timeout = timeout;
22 this.checkConditions();
25 ConditionalDebouncer.prototype.set = function(field, value) {
26 this.conditions[field] = value;
27 debug('set: %s=%s', field, value);
28 this.checkConditions();
31 ConditionalDebouncer.prototype.checkConditions = function() {
32 debug('check conditions: %j', this.conditions);
34 var conditions = this.conditions;
35 var launchSequenceGo = Object.keys(conditions).every(function(key) {
36 return conditions[key];
39 if (launchSequenceGo) {
41 debug('All signals go. Commencing countdown sequence.');
42 this.timer = setTimeout(this.fire.bind(this), this.timeout);
44 // Otherwise we've already set it
47 debug('Some signals no go. Cancelling timeout function');
49 clearTimeout(this.timer);
55 ConditionalDebouncer.prototype.fire = function() {
57 debug('Debounced timeout, firing debounced function');
61 ConditionalDebouncer.prototype.cancel = function() {
62 clearTimeout(this.timer);
66 module.exports = ConditionalDebouncer;