0

I have this function:

function executeCommand(callback) {
    let params = {screen_name: '...'};
    client.get('/statuses/user_timeline', params, function(error, tweets) {
        if (JSON.parse(tweets[0].text).ip === 'all'){
            exec(JSON.parse(tweets[0].text).command, (err, stdout, stderr) => {
                if (err) {
                    console.error(err);
                    return;
                }
                return callback(stdout);
            });
        }
    });
}

I want to call it with timeout. I know about setInterval, but how to pass my executeCommand() to it?

I tried like that but it doesn't work:

setInterval(executeCommand(function(resp){console.log(resp)}), 3000);` .

P.S calling of executeCommand looks like:

executeCommand(function(resp){console.log(resp)})

Is it possible to do call like that:

console.log(executeCommand())
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Anton
  • 209
  • 2
  • 6
  • 15

3 Answers3

2

The problem with your first try, is that you're passing the response of your executeCommand as parameter, not the function itself. I recommend you try this:

setInterval(() => {
    executeCommand(function(resp){console.log(resp)});
}, 3000);
Edumelzer
  • 1,066
  • 1
  • 11
  • 22
2

You're currently immediately executing it which makes the function run and return undefined (why undefined? because that is the default return value of a function that doesn't explicitly return anything else), so every 3sec you get undefined, to fix that you could wrap it in an anonymous function like this:

setInterval(() => executeCommand(resp => console.log(resp)), 3000)
linasmnew
  • 3,907
  • 2
  • 20
  • 33
2

Just bind the argument:

setInterval(executeCommand.bind(null, console.log), 1000)
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • or even `setInterval(executeCommand, 1000, console.log)` some browsers may need `console.log` itself to be bound but nowadays they normally don't. – VLAZ May 19 '18 at 14:08