Run While Typing

September 7, 2016 by Alex Thompson

For experimenting with small amounts of code I've always felt unsatisfied with the experience of a REPL. There's some great ideas out there for alternative environments in the realm of live programming and Bret Victor's demos. In the long run I hope to create some tools that achieve those utopian ideals but in the meantime I really just want a lean and mean environment that can run while typing.

run.primoca.com is my live editor for javascript. While it would be simple to just eval() code to get results a more sophisticated approach to execution is helpful. I've found injecting the code into a web worker to be the best trade off. A web worker runs on a separate thread so the UI can stay responsive even with CPU bound code. Creating a worker has low enough overhead that we can create a new one on each keystroke giving us a clean global scope on each run. A worker can also be terminated.

For getting results out to the UI we use postMessage() (also has a hook for console.log). This is also nice for asynchronous things like testing REST API's. Output is displayed to the right of the editor in sequential order. I like having the output in the same position over successive runs. I can see if it changed out of the corner of my eye while keeping my main focus on the code. The overall experience is basically supercharged printf debugging which I find very pleasant especially when the feedback loop is under 100ms.

For testing UI code there is an IFrame mode. It has more overhead since we still want a fresh global scope on each run and so a slightly slower feedback loop. Side rant: I think its absurd that JSFiddle does a round trip to the server for each run. That alone makes it impractical for them to have a run while typing feature due to server load. In contrast I store and load the code locally out of indexeddb.

Tags: programming