felixhao28 / JSCPP

A simple C++ interpreter written in JavaScript

Home Page:https://felixhao28.github.io/JSCPP/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Infinite loops

pqm opened this issue · comments

commented

Is there a way to stop code that has infinite loops?

Maybe something like counting steps in https://github.com/NeilFraser/JS-Interpreter, so if the number of steps is exceeded an error can be shown instead of freezing the browser, or the execution limit in https://github.com/codecombat/esper.js which sets a limit # of execution nodes.

It is very easy to add conditions here to stop the execution anytime you like.

like this:

startTime = Date.now()
loop
    step = mainGen.next()
    break if step.done
    break if Date.now() - startTime > 5000

Now that both "maxTimeout" option (to stop the program) and WebWorker support (to stop freezing the browser) is added, I think we can close it for now.

var helper = new JSCPP.WebWorkerHelper("./JSCPP.es5.min.js"); // it is a class
var output = "";
helper.run(`#include<stdio.h>
int main() {
    while(true == true){
        
    }
    return 0;
}`, "", {
    stdio: {
        write: function(s) {
            output += s;
        }
    },
    maxTimeout: 5000
}, function (err, returnCode) {
    if (err.message === "Time limit exceeded.") {
        alert("Program did not finish in 5000ms, possiblely due to an infinite loop.");
    } else if (err) {
        alert("An error occurred: " + (err.message || err));
    } else {
        alert("Program exited with code " + returnCode);
    }
});

helper.worker.terminate(); // directly control the Worker instance