0

why doesn't setTimeout work in this example? It runs immediately.

!function() {
    'use strict';

    function timeOut(str) {
        setTimeout(myFuction(str) , 3000);
    }

    function myFuction(a) {
        console.log(a);
    }

    timeOut("Hi"); //calling
}();

I expect myFunction to be run with passed value after 3 seconds. I know the other way. I just want to know why this doesn't work.

The working one:

!function() {
    'use strict';

    function myFunction(str) {
        console.log(str);
    }

    setTimeout(function() {
        myFunction("Hello")
    }, 3000);
}();
RamenChef
  • 5,533
  • 11
  • 28
  • 39
Meysam
  • 185
  • 7
  • 4
    You're doing it wrong. You need to pass a _function reference_ to `setTimeout`. When you do `myFunction(str)` you are _executing_ the function. You can wrap that in a new function or do `setTimeout(myFunction, 3000, str)` – VLAZ Nov 01 '16 at 21:21
  • @JJJ good, I was just searching for a dupe. We probably need that in the documentation - I can't seem to find a topic there for "How to use setTimeout/Interval" – VLAZ Nov 01 '16 at 21:24
  • @vlaz how can that anonymous function in the second example(working one) be a _function reference_ with those parenthesis in front of it, but first one is a _execution_ – Meysam Nov 01 '16 at 21:26
  • because `function() { /* some code */ }` defines a function - it's the same as you defining `myFunction`. It lacks a name, hence it's usually called an _anonymous_ function. Only it returns a reference. Once you have a function, however, putting `()` at the end (with or without parameters) executes it. – VLAZ Nov 01 '16 at 21:29

0 Answers0