Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout - callback argument must be a function

My code was working until i updated node.js to version 8.11.3

Now i always get error "callback argument must be a function" when trying to call a function with setTimeout.

function testFunction(itemid, price) {

  var url = 'https://example.com';
  var options = {
  method: 'get',
  url: url
  }

  request(options, function (err, res, body) {
    var response = JSON.parse(body);

     if(response.status == 'fail'){
        setTimeout(testFunction(itemid, price), 100);
     }
  })

}
like image 856
MHB2011 Avatar asked Aug 04 '18 12:08

MHB2011


3 Answers

Callback argument for setTimeout must be a function. Write it like this. Not tested but it should work.

function testFunction(itemid, price) {

    var url = 'https://example.com';
    var options = {
        method: 'get',
        url: url
    }

    request(options, function (err, res, body) {
        var response = JSON.parse(body);
        if(response.status == 'fail'){
            setTimeout(function () {
                testFunction(itemid, price);
            }, 100);
        }
    })
}
like image 199
Keyur Ramoliya Avatar answered Oct 21 '22 10:10

Keyur Ramoliya


@keyur is correct. According to the node.js timers documentation the setTimeout function takes the name of the function to execute as the first argument, the delay in milliseconds as the second argument, followed by any arguments being passed to the function.

For Example:

setTimeout(testFunction, 100, itemid, price);
like image 40
Nate Avatar answered Oct 21 '22 12:10

Nate


Yes, setTimeout() expects first argument as callback function. we can make use of es6 fat arrow function here you can try this!

setTimeout(() => testFunction(itemid, price), 100);

Hope this helps!

like image 3
Sk96 Avatar answered Oct 21 '22 12:10

Sk96