0

In my JavaScript code, inside the setTimeout() the value of a variable btnIdValue is not changing. It's showing a constant value 0. As this iterates through the loop the value was supposed to be changing. The minimum value for btnIdValue is set to 1.

$('#clearBtn').click(function(){
    btnIdValue = $('#inputTxtBx').val();
    while( btnIdValue > 0  ){
        setTimeout(function() {
            alert(["#circle",btnIdValue].join(''));
            $(["#circle",btnIdValue].join('')).remove();
            $(["#button",btnIdValue].join('')).remove();
        }, 1000);
        alert(btnIdValue);
        btnIdValue--;
    }
});

I am trying to remove elements with id. When i issued the hard-coded values, it works.

$("#circle1").remove();
$("#button").remove();

I tried the below part inside a loop, but it removes all the elements without the desired delay and remove effect.

$(["#", btnIdValue].join('')).delay(1000).fadeOut(1000, function(){
    $(this).remove();
}); 
anjo
  • 315
  • 2
  • 7
  • 18
  • Why would use use array and join instead of a simple `"#circle" + btnIdValue`? – epascarello Nov 19 '15 at 13:11
  • Do have a look at the duplicate although it's a little hard to link `setTimeout` with the closure examples in the answer. In your case, it's not a closure issue (so I disagree with it being a duplicate) but rather a *concurrency issue* - what your code is actually doing is `while (val>0) { val--; } $("#.."+val).remove();` The `setTimeout` code runs *after* the val has already been set to 0. – freedomn-m Nov 19 '15 at 13:18
  • In your code setTimeout will execute after finishing while loop.. thats why last value of btnIdValue ie 0. setTimeout is meaningless here. – Tushar D Nov 19 '15 at 13:54

0 Answers0