Created
October 2, 2014 17:57
-
-
Save simenbrekken/16efd96373b207ad7bdc to your computer and use it in GitHub Desktop.
Eventually – Debounce for promises
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| '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