Skip to content

Instantly share code, notes, and snippets.

@simenbrekken
Created October 2, 2014 17:57
Show Gist options
  • Select an option

  • Save simenbrekken/16efd96373b207ad7bdc to your computer and use it in GitHub Desktop.

Select an option

Save simenbrekken/16efd96373b207ad7bdc to your computer and use it in GitHub Desktop.
Eventually – Debounce for promises
'use strict';
var Promise = require('bluebird')
function eventually(callback, wait, leading) {
var timer
return function() {
var context = this
var args = arguments
var resolve
var called
var promise = new Promise(function(deferred) {
resolve = deferred
}).then(function() {
return callback.apply(context, args)
})
if (leading) {
if (timer) {
called = true
} else {
resolve()
}
}
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(function() {
timer = null
if (!leading || called) {
resolve()
}
}, wait)
return promise
}
}
module.exports = eventually
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment