Wednesday, March 03, 2010

March Madness Challenge - Day 3

Another long day, but I did come. up with something that I needed for another project. It turns out the closest thing Javascript has to sleep(ms) or delay(ms) is setTimeout. Which is nice but is tricky to use in a synchronous environment. So in terms of matching what happens on an AVR chip or an Arduino. It's time for a delay(ms) script.

setTimeout("showColor(red,green,blue)",holdTime);


function showColor(red, green, blue)
{
document.getElementById("leddisplay").style.backgroundColor="rgb(" + red + "," + green + "," + blue + ")";
}


Well not really. I wrote the delay function, but it's not the recommended technique. Why block all actions on a page waiting for one thing to happen. The above code is closer. But doesn't solve the key issues. The setTimeout needs to have values assigned for red, green, and blue for the showColor function. Additionally, this code requires a web page. I needed to upload that. I needed to assign an event listener, and lastly had to resolve an issue about setTimeout being inside a loop. The issue being the loop sets all the "setTimeout"s as quickly as possible, so all time outs occur almost in parallel. I could be wrong about that, but I did have some kind of issue. I needed to examine Javascript fader examples more closely, and I would have figured it out, but ran out of time.

Ok. I wrote a super quick brute force demonstration of the problem. This requires Firebug in order to run. Paste the following code into the Firebug console. Warning whatever web page you are viewing in firebug will go through some awful color contortions.

function showColor(red, green, blue)
{ document.body.style.backgroundColor="rgb(" + red + "," + green + "," + blue + ")";
console.log("Color set");
}
console.log("Start");
console.log('setTimeout("showColor(0,0,0)",10000);');
setTimeout("showColor(0,0,0)",10000);
console.log('setTimeout("showColor(10,10,10)",9000);');
setTimeout("showColor(10,10,10)",9000);
console.log('setTimeout("showColor(100,100,100)",8000);');
setTimeout("showColor(100,100,100)",8000);
console.log('setTimeout("showColor(200,200,200)",7000);');
setTimeout("showColor(200,200,200)",7000);
console.log('setTimeout("showColor(200,0,0)",6000);');
setTimeout("showColor(200,0,0)",6000);
console.log('setTimeout("showColor(100,0,0)",5000);');
setTimeout("showColor(100,0,0)",5000);
console.log('setTimeout("showColor(0,100,0)",4000);');
setTimeout("showColor(0,100,0)",4000);
console.log('setTimeout("showColor(0,100,100)",3000);');
setTimeout("showColor(0,100,100)",3000);
console.log("Done")


So nesting the setTimeout inside SetTimeout should be interesting. Onto the next challenge.

No comments: