Skip to content
Arjun Guha edited this page Jul 30, 2020 · 4 revisions

Quick Start

Consider the following JavaScript program that runs forever and periodically prints the current time:

const elt = document.createElement("div");
document.body.appendChild(elt);

var i = 0;
var j = 0;
while (true) {
    if (i++ == 10000000) {
        j++;
        elt.innerText = "Still running ... " + (new Date());
        i = 0;
    }
}

Since the program never yields control to the browser's event loop (e.g., using setTimeout), nothing will appear on the page and the browser tab will eventually crash. Stopify will make this program behave more naturally and actually show the time.

First, we'll create a web page that loads the Stopify library:

<html>
  <body>
    <script src="https://github.com/plasma-umass/Stopify/releases/download/0.7.2/stopify-full.bundle.js"></script>
    <script>
    const program = `
        const elt = document.createElement("div");
        document.body.appendChild(elt);

        var i = 0;
        var j = 0;
        while (true) {
            if (i++ == 10000000) {
                j++;
                elt.innerText = "Still running ... " + (new Date());
                i = 0;
            }
        }
    `;

    const asyncRun = stopify.stopifyLocally(program);
    asyncRun.g = { document, Date };

    asyncRun.run(() => { console.log('Terminated'); });
    </script>
  </body>
</html>

Save the code above in a .html file, open it in a web browser, and it works! Some things to note:

  1. The `program' variable holds the source code of the original program. Stopify compiles the program in the web browser, and you can load a new program at any time.

  2. The line asyncRun.g = { document, Date } defines the global environment for program. You can add other functions and objects to the global environment.

  3. The line asyncRun.run(() => { console.log('Terminated'); }); runs the program asynchronously, and calls the callback function that prints "Terminated" when the program completes. In this case, since the program runs forever, "Terminated" will never print.