April 14th, 2009

Hungry snail!

MCU development and JavaScript

I was looking into using JavaScript to run some of my MCU programs, and I found myself reprogramming and tweaking the algorithms rather than just refactoring the code.

All the JavaScript animation programs I've seen implement the setInterval or setTimeout functions to regularly halt the code so that the display gets a chance to be updated.

Take this code for instance:

loop from x=0 to x=1000
...move DIV tag to 'x' location
next loop

When run, there is no animation - the DIV tag appears at 'x' location 1000. If you put this in an endless loop - the DIV never appears, and the JS engine locks up - waiting for the JS to end so it can update the HTML which will never happen.

Changing this code to use the setInterval function is easy -


func updatePos()
...move DIV to x
...if x=1001 anim=none

But notice how the code is completely different?
It gets a lot worse with a proper program - phase states have to be saved, loops emulated, lots of restructuring.

What I'm trying to do now, is to find some way of running an iteratively driven (rather than clock driven) JavaScript program that wont freeze the browser, will update the display, and retain the structure of the MCU program I'm emulating.

Has anyone got any cool and original ideas for me to try out?

( http://jsninja.com/Timers ... not much inspiration here...)

Firefox only - I've added a "short pause" and "long pause" function. short-pause is CPU MHz dependent, but enables a script to run faster than 1ms each iteration without locking the browser.


<div id="box" style="position:absolute; top:50px; left:0px; width:100px; height:100px; background-color:#000000;"></div>


var thread = Components.classes["@mozilla.org/thread-manager;1"].getService(Components.interfaces.nsIThreadManager).currentThread;


function longPause(delay)
   this.delayed = true;
   while (this.delayed)

function shortPause(delay)
   this.delayed = 0;
   while (this.delayed++<delay)