1
var test = function(a, b) {   return a + b; }; 
setTimeout(test(2, 3), 3000);

it shows some type error

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55

2 Answers2

2

There are at least two ways to achieve this. The first one just fires the test function inside of a new anonymous function passed as callback to the setTimout.

The second one uses .bind to partially apply the test function.

var test = function(a, b) {
  console.log(a + b);
  return a + b;
};

setTimeout(() => {
  test(2, 3);
}, 3000);

setTimeout(test.bind(null, 2, 3), 3000);

And if you don't like the first (in this case meaningless) argument null of .bind as I do, then you can use some library that provides you with partial application functionality or you can write your own function that performs partial application.

const partial = (fn, ...firstArgs) => (...secondArgs) =>
  fn(...firstArgs, ...secondArgs);

var test = function(a, b) {
  console.log(a + b);
  return a + b;
};

setTimeout(partial(test, 2, 3), 3000);
Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54
0

This is the right way to call an external function inside setTimeout

var  test = function(a, b) { return a + b; };     
setTimeout(function() {test(2, 3)} , 3000)
Vizag
  • 743
  • 1
  • 7
  • 30
J Prakash
  • 1,323
  • 8
  • 13
  • You have enough rep to flag to close the question as duplicate. Please don't post an answer when you are aware that there is a duplicate question with answers much better than yours available. – Nisarg Shah May 26 '18 at 07:21