-2

So I have this piece of code...

 var string = 'qwe';

 document.addEventListener('click', function(e){

    function bar(b){

       var a = string[b];
       if (a == 'q') {
          console.log('first');
       }
       if (a == 'w') {
          console.log('second');
       }
       if (a == 'e') {
          console.log('third');
       }

    }       
    setTimeout( bar(0), 1000 );
});

Problem is setTimeout doesn't work. Code executes right after clicking.

It's weird because if I avoid using the closure, it works...

setTimeout(function bar(){
   var a = string[0];
   //...everything else
},1000 );

But that would probably make the code messy/redundant, since I plan on doing it 3 times. Ideally the working code would be...

setTimeout( bar(0), 1000 );
setTimeout( bar(1), 2000 );
setTimeout( bar(2), 3000 );

But again, setting timeOut like this doesn't work for some reason :/ Any ideas why?

Magdi Gamal
  • 681
  • 1
  • 9
  • 25
  • 4
    Use `setTimeout( () => bar(0), 1000 )` to queue a function. You just queue the **result** of the function. – Sirko Sep 01 '17 at 07:21
  • Your executing the function immediately. 'bar(0)'. Ironically creating a closure would help, but here you have just made a plain function. – Keith Sep 01 '17 at 07:24
  • Given `foo(bar())`, `bar` is always executed first and its return value is passed to `foo`. This behavior doesn't magically change for `setTimeout`. – Felix Kling Sep 01 '17 at 07:27

1 Answers1

0
setTimeout( bar(0), 1000 );

over here setTimeout expects a function but it gets bar(0). hence while try to initialise bar(0) is called, you have to use

setTimeout( () => bar(0), 1000 ) 

to make it work, since now it is returning a function

marvel308
  • 10,288
  • 1
  • 21
  • 32
  • 1
    Please look for duplicates for such basic questions. Answering a possible dupe can attract unwanted comments/votes – Rajesh Sep 01 '17 at 07:25
  • yes I see it is a possible duplicate of the question but it also answers why bar(0) was called immediately – marvel308 Sep 01 '17 at 07:30