javascript - multiple setTimeout calls within a for loop -
i'm trying code game simon in html/js , it's working, except part game flashes sequence know new sequence is. have is:
for(var in thepattern){ var obj = document.getelementbyid(thepattern[i]); window.settimeout(coloron(obj),500); window.settimeout(coloroff(obj),1000); } where coloron , coloroff are:
function coloron(obj){ if(obj.id == "red"){ obj.style.backgroundcolor="#ff5555"; }else if(obj.id == "blue"){ obj.style.backgroundcolor="#5555ff"; }else if(obj.id == "green"){ obj.style.backgroundcolor="#88ff88"; }else{ obj.style.backgroundcolor="#ffffaa"; } } function coloroff(obj){ if(obj.id == "red"){ obj.style.backgroundcolor="#ff0000"; }else if(obj.id == "blue"){ obj.style.backgroundcolor="#0000ff"; }else if(obj.id == "green"){ obj.style.backgroundcolor="#22ff22"; }else{ obj.style.backgroundcolor="#ffff00"; } } what seems doing going through entire loop , starting timers , then timers go off colors don't seem flash.
any ideas? appreciated.
now flashing correctly , closure working correctly, flashing colors @ same time. i've tried putting closure within settimeout, however, creates other problems.
solved guys.
you need pass function settimeout:
window.settimeout(function() { coloron(obj); },500); right now, you're calling coloron(obj) , passing output settimeout, makes appear settimeout firing immediately.
obj passed reference, time of functions run, obj refer last element in loop. around that, have pass obj value shadowing it:
(function(obj) { window.settimeout(function() { coloron(obj); }, 500); window.settimeout(function() { coloroff(obj); }, 1000); })(obj);
Comments
Post a Comment