0

I am trying to play around with callback functions. I wanted to make my callback async and from what I understand, one of the ways is to call the setTimeout function to make my synchronous function, async. This works well, unless I try to pass an argument to my callback in setTimeout:

This is async:

var callback_function = function (funcArg) {
    console.log("From Main Function");
    setTimeout(funcArg, 10); // WATCH THIS LINE
    console.log("From Main Function 2");
};

callback_function(function (arg) {
    console.log("From Callback");
    console.log(arg);
});

console.log("This should run before callback");

Output:
From Main Function
From Main Function 2
This should run before callback
From Callback
undefined

This is not async:

var callback_function = function (funcArg) {
    console.log("From Main Function");
    setTimeout(funcArg("Test"), 10); // WATCH THIS LINE
    console.log("From Main Function 2");
};

callback_function(function (arg) {
    console.log("From Callback");
    console.log(arg);
});

console.log("This should run before callback");

Output:
From Main Function
From Callback
Test
From Main Function 2
This should run before callback

Any idea why this is happening? And how can I run the function asynchronously despite passing in an argument?

Community
  • 1
  • 1
nknj
  • 2,436
  • 5
  • 31
  • 45
  • possible duplicate of [How can I pass a parameter to a setTimeout() callback?](http://stackoverflow.com/questions/1190642/how-can-i-pass-a-parameter-to-a-settimeout-callback) – nknj Feb 10 '14 at 11:49

1 Answers1

2

You're not passing a function to setTimeout but calling your function and passing the result.

Change

setTimeout(funcArg("Test"), 10);

to

setTimeout(function(){ funcArg("Test")}, 10);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758