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);
5 Answers 5
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.
Comments
In your 2nd example it is immediately calling test with the string xxx.
Comments
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);
Comments
If you write a function name with parenthesis, it will call it instead giving reference.
Comments
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.