0

I was just wondering;

Why does this work;

 test = function(message) {
 console.log('xxx');
 }
 setTimeout(test, 3000);

but not this;

 test = function(message) {
 console.log(message);
 }
 setTimeout(test('xxx'), 3000);

I know it should be written like this; But the version above would be so much more convenient...

 test = function(message) {
 console.log(message);
 }
 setTimeout(function() { test('xxx'); }, 3000);
Daniel A. White
192k49 gold badges389 silver badges474 bronze badges
asked Jul 26, 2015 at 1:17
0

5 Answers 5

1

You're assigning the returned result of test to the callback argument of setTimeout instead of passing the function reference.

function callback(callback) {
 callback();
}
function say(message) {
 console.log(message);
 // this function doesn't return anything
}
// callback(say('Hello World!')) === callback() because say(message) doesnt return anything.
answered Jul 26, 2015 at 1:23
Sign up to request clarification or add additional context in comments.

Comments

0

In your 2nd example it is immediately calling test with the string xxx.

answered Jul 26, 2015 at 1:19

Comments

0

You are calling the function immediatly in your second example. To pass the string, you can bind the parameter instead of calling it on its own:

setTimeout(test.bind(null,'xxxx'), 3000);

 test = function(message) {
 alert(message);
 }
 setTimeout(test.bind(null,'xxxx'), 3000);

answered Jul 26, 2015 at 1:20

Comments

0

If you write a function name with parenthesis, it will call it instead giving reference.

answered Jul 26, 2015 at 1:21

Comments

0

The second one doesn't work because setTimeout requires a function as a parameter (which it will call) and the second version you show has test('xxx') which means "the result of calling test('xxx')" which is undefined - not a function.

answered Jul 26, 2015 at 1:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.