2

Javascript is executing this code instantly, however, I need it to wait 2 milliseconds before executing it, as scripted in setTimeout(doIt(i),2000);

Why?

<script type="text/javascript">
    var colors= ["red","pink","green"];
    function doIt(i){
        i++
        console.log(i);
        console.log("didIt");
        $('body').append("<style>body{background:"+i+";}</style>");
        if(i==2){
        }
        else{
            test(i);
        }

    }

    function test(i){
        setTimeout(doIt(i),2000);
    }
    test(0);
</script>
Shashank Agrawal
  • 21,660
  • 9
  • 71
  • 105
kirill2485
  • 347
  • 1
  • 5
  • 21
  • `setTimeout` first argument is a reference to a function – zerkms Aug 09 '16 at 04:48
  • Difference between a function expression and a function invocation: the parentheses. One is a function, the other is a value that is returned by the function. – Guybrush Threepwood Aug 09 '16 at 04:51
  • Tutorial here: http://www.jquerybyexample.net/2014/11/javascript-settimeout-executes-function-immediately.html – Jaime Aug 09 '16 at 04:51

1 Answers1

4

This is the most common mistake. Change your code to this:

function test(i){
    setTimeout(function() {
        doIt(i);
    }, 2000);
}

You were directly invoking the doIt method instead of just passing the reference to the setTimeout callback by writing (i) after doIt.

Another way of writing directly using the bind() method:

function test(i) {
    setTimeout(doIt.bind(null, i), 2000);
}

It's all given here:

  1. How can I pass a parameter to a setTimeout() callback?
  2. Calling functions with setTimeout()
Community
  • 1
  • 1
Shashank Agrawal
  • 21,660
  • 9
  • 71
  • 105