Reputation: 634
I have a function that I used to add a status indicator to a div when a process is running and to remove it when that process is done. The problem I'm having is when multiple functions are being processed and finish, the working_handle only removes the first processes working state.
if I remove the setTimeout portion of the code, it works perfectly, however I want a delay on it as it happens so quickly it a bit jarring.
function working_handle(id, state) {
idh = id.replace(/^#/, '');
if (state === true) {
console.log('WORKING'+'-'+idh);
$(id).removeClass('error').addClass('working');
$('#status').removeClass(idh+'-error').addClass(idh+'-working');
} else {
console.log('DONE'+'-'+idh);
setTimeout(function() {
$(id).removeClass('working');
$('#status').removeClass(idh+'-working');
}, 2000);
}
}
Upvotes: 0
Views: 83
Reputation: 101680
You do not have var
(or const
or let
) before idh
, which makes it an implicit global. This means that every call to your function is sharing the same closure variable and overwriting its value.
To fix the problem, declare it so that it is scoped to the function:
var idh = id.replace(/^#/, '');
I would also advise adding the "use strict" pragma to the top of your JS files, which will help to catch issues like this. Implicit globals are bad news.
Upvotes: 1