mikemaccana
mikemaccana

Reputation: 123148

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:

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

Answers (1)

G07cha
G07cha

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

Related Questions