Skip to content

Instantly share code, notes, and snippets.

@icodeforlove
Last active December 28, 2015 19:59
Show Gist options
  • Select an option

  • Save icodeforlove/7554043 to your computer and use it in GitHub Desktop.

Select an option

Save icodeforlove/7554043 to your computer and use it in GitHub Desktop.
easy way to throttle async tasks
function AsyncTaskThrottle () {
this._queued = null;
this._busy = false;
}
AsyncTaskThrottle.prototype = {
do: function (task) {
if (!this._busy) {
this._queued = task;
return this._call();
} else {
this._queued = task;
}
},
_call: function () {
if (this._busy || !this._queued) return;
var self = this,
task = this._queued;
this._queued = null;
this._busy = true;
task(function () {
self._busy = false;
self._call();
});
}
};
var taskThrottle = new AsyncTaskThrottle();
setInterval(function () {
taskThrottle.do(function (callback) {
setTimeout(function () {
console.log('called');
callback();
}, 500);
});
}, 50)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment