-6

I wonder how i can shorten my program.

function versteigern(objekt){

    for(var i = 1; i<=3; i++){
        if(i === 1){
            setTimeout(function(){console.log(objekt + " zum 1")},1000*i);
        }
        else if(i === 2){
            setTimeout(function(){console.log(objekt + " zum 2")},1000*i);
        }
        else if(i === 3){
            setTimeout(function(){console.log(objekt + " zum 3")},1000*i);
        }
}

Because I feel like that's not the optimal solution since i'm using if-else.

Martin G
  • 17,357
  • 9
  • 82
  • 98

1 Answers1

0

You can use this code, then it should work like you want it wo work:

function versteigern(objekt) {
  for(var i = 1; i <=3; i++) {
    setTimeout(function(x) { return function() { console.log(objekt + " zum " + x); }; }(i), 1000*i);
  }
}
Martin G
  • 17,357
  • 9
  • 82
  • 98
Philip
  • 153
  • 10
  • But it doesn´t work this way. The result would be 4. console.log would return 4, I tried it this way. Here is a link, why it won´t work: http://brackets.clementng.me/post/24150213014/example-of-a-javascript-closure-settimeout-inside – Philip Nov 18 '15 at 08:48