1

I want to set 8 timeouts from a for loop. i have jquery ids: ir1,ir2...,ir8. Why is the following not working:

        var i = 1;
        for (i; i<9; i++ ){
            setTimeout( $('#ir'+i).hide(),100*i);
        }

3 Answers 3

1

http://jsbin.com/OrUVoRi/1/edit

  var i = 0, elements = [];
  //save jquery calls for performance reasons
  for (i = 0; i<9; i++){
    elements[i] = $('#ir'+i);  
  }
  //you can make this function custom
  var hide = function(i){
    elements[i].hide();
  };
  //the callback loop
  for (i = 0; i<9; i++){
    //bind i value to the hide function
    setTimeout( hide.bind(this, i), 1000*i );
  }
Sign up to request clarification or add additional context in comments.

Comments

0

setTimeout() should be

setTimeout(function(){
   $('#ir'+i).hide()
},100*i);

updated.

as @royi namir mentioned, the issue is because of closure(scope) , call a self invoking function , pass i as argument , increased the timeout value to 1000 ... just as an example

  var i = 1;
    for (i; i<9; i++){
        (function(a){
            setTimeout(function(){
                $('#ir'+a).hide();
            },1000*a);
        })(i);
    }

fiddle

1 Comment

not working. Neither does: setTimeout(function(i){ $('#ir'+i).hide() }(i),1000*i);
0

You question is blurred : I'll explain :

in first glance you're having a closure problem :

solution :

 var i = 1;
    for (i; i<9; i++){
        (function(a){
            setTimeout(function(){
                $('#ir'+a).hide();
            },1000*a);
        })(i);
    }

Also , since all your timeouts execute in burst -you added an increased delay : 100*i;

Among other solutions - here is mine : http://jsbin.com/EpaceSaJ/5/edit

the difference is that in your case - the functions will be at exact 100*i regardless the execution of inner code While - in my solution : the timeout will be start after each end of last operation.

(function g(i,max){

   setTimeout(function   ( )
   {
       console.log(i); // <-- put your stuff here
      if (i==max) return false;
       g((++i),max);
   }, 1000); 
})(1,3); // <--loop  values from 1 to 3 (9 at your case)

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.