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);
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.
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.

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);

Comments

0

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

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.

Comments

Your Answer

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.