Reputation: 123148
I know what debounce does. I'd like to trigger it in node (by running a script with #!/usr/bin/env node
), but I'm having trouble.
The code below should:
doThingAfterDelay()
which runs a simply function after it has been called once and not been called again for 100ms.doThingAfterDelay()
doThingAfterDelay()
time to debounce and therefore execute.However it doesn't work:
var log = console.log.bind(console),
_ = require('lodash')
var doThingAfterDelay = _.debounce(function(){
return 'foo'
}, 100);
log(doThingAfterDelay());
setTimeout(function(){
log('Sleeping')
}, 15 * 1000)
It returns:
undefined
Sleeping
I expected:
foo
Sleeping
How can I make the debounced function run?
edit: I can get the desired output with:
var log = console.log.bind(console),
_ = require('lodash')
var doThingAfterDelay= _.debounce(function(){
log('foo')
}, 100);
doThingAfterDelay('one', 'two');
setTimeout(function(){
log('Sleeping')
}, 15 * 1000)
But I do not understand why - and it is important that doThingAfterDelay()
returns a real value.
Upvotes: 1
Views: 1834
Reputation: 4154
If you have a look at source code of the debounce function you can find that it uses setTimeout
under the hood and therefore has the same mechanic. You can use a callback or Promise to pass value after debounced function will be executed(also if you are using Promise you could make your code look more synchronous with async/await).
var log = console.log.bind(console),
_ = require('lodash')
var delayedResults = new Promise(function(resolve) {
_.debounce(function(){
resolve('foo');
}, 100)();
});
var start = async function(){
log(await delayedResults )
}
start()
Upvotes: 2