You will find it easier to loop with jQuery.each()
rather than for()
. The .each()
callback function will automatically trap the var you need, so there's no need to make another, inner closure.
The most likely thing that's preventing the click handler from working is listenerKind
. If no such member exists, then an error will be thrown and the event thread will die.
Your biggest issue is knowing when to change the "in progress" message to "complete". As it stands, the message will change back immediately without waiting for any of the setTimeouts to complete, let alone all of them.
Personally, I would do something like this (see comments in code) :
function runSimulation() {
var $agents = $("div.tooltipBox"),
$rFOs = $(".rFO"),
$message = $("#lContent h2");
if($agents.filter('.running').length > 0) {
//Inhibit simulation if any part of an earlier simulation is still running.
return;
}
$message.html("Simulation <b>in progress...</b>");
$agents.each(function(i, agent) {
var ttl, $agent;
if(i >= $rFOs.length) {
return false;//break out of .each()
}
ttl = Number($rFOs.eq(i).val());//Any failure to cast as Number will result in NaN.
if(isNaN(ttl)) {
return true;//continue with .each()
}
$agent = $(agent).addClass('running');//Provide a testable state (see below and above)
$agent.children(".tttFalloutOrder").on('click.sim', function() {//Note: namespaced click event allows .off('click.sim') without affecting any other click handlers that might be attached.
alert("click on " + $agent.attr('id'));
});
setTimeout(function() {
$agent.children(".tttFalloutOrder").off('click.sim');//detach the handler attached with .on('click.sim') .
$agent.removeClass('running').children(".offlineCover").fadeIn(500);
if($agents.filter('.running').length == 0) {//if neither this nor any other agent is "running"
$message.html("Simulation <b>complete</b>");//Signify complete when all parts are complete
}
}, ttl*1000);
});
}
untested
If it the click actions still don't work, then I would suspect the $agent.children(".tttFalloutOrder")
selector to be incorrect.
There are other ways of doing this type of thing, notably ways that exploit Deferreds/promises and jQuery.when()
, but the above code (suitably debugged) should suffice.