How to suspend JavaScript to allow render

2019-07-24 19:28发布

I have a little script that runs a simulation, of which I want to render the results 'live':

for ( i < simulation steps ) {
    do_simulation();
    render_with_flot();
}

I noticed that the plot only gets rendered after the last step.

  • Is there a way to 'suspend' javascript somehow to allow the rendering to run after each iteration?
  • Or is there a way to make flot run synchronously?
  • Or do I need to set my own timeouts for each iteration of the for-loop? This seems like kind of a hassle.

2条回答
地球回转人心会变
2楼-- · 2019-07-24 19:53

Depends how fast it needs to run, but the best way would be to use SetInterval

Pseudocode / hand-written-javascript-that-probably-doesnt-run:

var PerformedSteps;
var Interval;

PerformedSteps = 0;
Interval = setInterval(work, 1000/60); //60 times/second

function work()
{
    PerformedSteps++;

    if (PerformedSteps == simulation_steps)
    {
        clearInterval(Interval);
        return;
    }

    do_simulation();
    render_with_flot();
}
查看更多
ゆ 、 Hurt°
3楼-- · 2019-07-24 20:02

As an alternative to @PhonicUK's solution, you could do a setTimeout() at the end of work() to schedule the next call to work(), giving the rendering a chance to happen & not tying yourself to any particular refresh rate.

查看更多
登录 后发表回答