I am trying to achieve the following things when I click an element using 3 setTimeouts:
- setTimeout1 = wait 500ms to add a class (that animates something to 100% progress)
- setTimeout2 = wait another 400ms to animate that element to scale(0) using a css class
- setTimeout3 = wait another 500ms to remove that element from the grid using jquery remove()
Whenever I am clicking fast another element, the previous setTimeouts from the previous clicked element are stopping and they run on the click, until you click another element and do the same.
Again, looking at the image above, if I click on the first item, setTimeout1 runs, and if I click on the other element, the other 2 setTimeouts stops and never run, but the last element clicked works just fine if I don’t click another one.
Here is my code below. What am I doing wrong here? Having only issues with the js timeouts, not with the css/html.
function complete_item_anim(obj) {
obj.find(".orderitemprogressbar_text_status").fadeOut(200);
obj.find(".orderitemprogressbar_text_done").fadeIn(200);
obj.find('.order_item_box').addClass('completed');
}
$(".grid-item").click(function(event) {
elem = $(this);
$(this).find('.oitpb_percent').text('100%');
$(this).find('.oitpb_time').text('0m');
$(this).find('.oitpb_time_group').css('max-width', 0);
$(this).find('.orderitemprogressbar_green').css('width', '100%');
setTimeout(function() {
complete_item_anim(elem);
setTimeout(function() {
elem.find('.order_item_box').addClass("removed");
setTimeout(function() {
elem.remove();
}, 500);
}, 600);
}, 600);
});
>Solution :
The problem is that you only have one elem variable, and if you click on another element, that elem variable is set to that element, meaning that the setTimeout callbacks that were supposed to work with the first element, will actually work with the second.
This is all solved if you apply the best practice to not use variables with implicit declarations, but to define them explicitly with var, or nowadays better with let or const. That will create a variable that is scoped to the click callback function, and so every execution of that callback will have its own elem variable, which is what you need here.
Not your question, but you should also deal with the case where you click the same element multiple times. In that case decide whether to cancel the earlier initiated setTimeout, or to ignore the second click and let those earlier timers do their job until completion.
