开发者

slow down execution of javascript's eval

I have created a little robot like the Karel robot (Wikipedia) which is based on javascript.

Karel4Web

The robot can be controlled with some simple commands such as "forward", "turnright" and so on.

The user can write a javascript program to control the robot which then goes through javascripts "eval()" function so that the robot moves.

The problem is that I want the robot to move slowly so that you can see what he is doing and so that you can highlight the current code line in the editor.

Current method: Parsing

At the moment I have solved this (in the offline version) by parsing each line in the textarea and then building a stack of action which are then executed one after another with window.setTimeout. But this is of course limited because I have to write parsing code for every little javascript language contruct which is much work and error prone.

Some additional information to this:

Parsing version: http://abi-physik.de/_niki2/niki.php

Parsing version js code: http://abi-physik.de/_niki2/js/niki.js

Important functions are at the bottom of the script: run(), execute()

I am currently parsing the user script line by开发者_C百科 line and adding the actions to a stack. If the parser encounters an "if" it will begin a new stack and add all actions to that stack. if the parser then encounters an "}" it will close the "if" stack and continue to add actions to the base stack.

Any idea to improve this?


I would say have those functions register to some queue instead of having them execute the JavaScript directly.

var moveQueue = [];

function forward(){
  moveQueue.push(_forward);
}
function _forward(){
    alert("move forward");
}

function backward(){
  moveQueue.push(_backward);
}
function _backward(){
    alert("move backward");
}

Than when it runs you would use a setTimeout and

function run(){
    var curStep = 0;
   function go(){
      moveQueue[curStep]();
      curStep++;
      if(curStep<moveQueue.length){
          window.setTimeout(go,500);
      }
   }  
}

You still would need to parse it out to figure out the if statement logic, but this is one of many ways that will allow you to control the speed of execution.


Javascript doesn't have a sleep() function, so yes, using setTimeout or setInterval is the way to go.

You could parse the 'instructions' first, assemble an array of actions that need to be carried out, then use setInterval to arrange for a function to be regularly called which takes the next instruction and carries it out (or clears the interval, if there are no more instructions waiting to be processed).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜