setTimeout - callback argument must be a function
17,111
Solution 1
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);
}
})
}
Solution 2
@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);
Solution 3
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!
Related videos on Youtube
Author by
MHB2011
Updated on May 24, 2022Comments
-
MHB2011 about 2 years
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); } }) }
-
Estus Flask almost 6 yearsThe code never worked as intended, FYI.
-
Patrick Hund almost 6 yearsAgreed, @MHH, you probably just didn't notice that
testFunction
was not called after 100 ms, but rather immediately – you weren't passing the functiontestFunction
as argument tosetTimeout
, but rather the result from calling it. Upgrading to Node 8.11.3 exposed your mistake, because it doesn't allow you to pass anything but a function anymore
-
-
Estus Flask almost 6 yearsit always requires a function as the callback argument - it doesn't.
setTimeout(<string>)
is a form of eval that was intentionally removed from Node implementation. -
Keyur Ramoliya almost 6 years@estus Don't about that. Revoking that line.