mikemaccana mikemaccana -4 years ago 92
Node.js Question

How can I run a debounced function from node command line?

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:


  • Make
    doThingAfterDelay()
    which runs a simply function after it has been called once and not been called again for 100ms.

  • Run
    doThingAfterDelay()

  • Sleep (asynchronously) for 15 seconds, giving
    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.

Answer Source

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download