Skip to content

Instantly share code, notes, and snippets.

@blasten
Last active November 16, 2016 22:51
Show Gist options
  • Save blasten/f6de5d88408a3aa52047d343ba15a272 to your computer and use it in GitHub Desktop.
Save blasten/f6de5d88408a3aa52047d343ba15a272 to your computer and use it in GitHub Desktop.
Polymer.Debouncer = function Debouncer() {
this._scheduler = Polymer.Async.microTask;
this._timer = null;
this._wait = 0;
this.flush = this.flush.bind(this);
};
Polymer.Utils.mixin(Polymer.Debouncer.prototype, {
after: function(scheduler, wait) {
this._scheduler = asyncModule;
this._wait = wait || 0;
return this;
},
go: function(callback, context) {
this._callback = context ? callback.bind(context) : callback;
this._timer = this._scheduler.run(this.flush, this._wait);
return this;
},
cancel: function() {
if (this._timer) {
this._scheduler.cancel(this._timer);
this._timer = null;
}
return this;
},
flush: function() {
if (this._timer) {
this.cancel();
this._callback();
}
return this;
},
isActive: function() {
return Boolean(this._timer);
}
});
Polymer.Debouncer.debounce = function(debouncer) {
return debouncer ? debouncer.cancel() : new Polymer.Debouncer();
};
Polymer.Async = {};
Polymer.Async.microTask = {
_currVal: 0,
_lastVal: 0,
_callbacks: [],
_twiddleContent: 0,
_twiddle: document.createTextNode(''),
run: function (callback) {
this._twiddle.textContent = this._twiddleContent++;
this._callbacks.push(callback);
return this._currVal++;
},
cancel: function(handle) {
var idx = handle - this._lastVal;
if (idx >= 0) {
if (!this._callbacks[idx]) {
throw 'invalid async handle: ' + handle;
}
this._callbacks[idx] = null;
}
},
_atEndOfMicrotask: function() {
var len = this._callbacks.length;
for (var i=0; i<len; i++) {
var cb = this._callbacks[i];
if (cb) {
try {
cb();
} catch(e) {
// Clear queue up to this point & start over after throwing
i++;
this._callbacks.splice(0, i);
this._lastVal += i;
this._twiddle.textContent = this._twiddleContent++;
throw e;
}
}
}
this._callbacks.splice(0, len);
this._lastVal += len;
},
flush: function() {
this.observer.takeRecords();
this._atEndOfMicrotask();
}
};
Polymer.Async.timeOut = {
run: window.setTimeout,
cancel: window.clearTimeout
};
Polymer.Async.rAF = {
run: window.requestAnimationFrame,
cancel: window.cancelRequestAnimationFrame
};
/* requestIdleCallback */
Polymer.Async.rIC = {
run: function(fn) {
var g = window;
return g.requestIdleCallback ? g.requestIdleCallback(fn) : setTimeout(fn, 16);
},
cancel: function(timer) {
var g = window;
g.cancelIdleCallback ? g.cancelIdleCallback(timer) : clearTimeout(timer);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment