How to suspend JavaScript to allow render

江枫思渺然 提交于 2020-01-05 08:18:45

问题


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.

回答1:


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.




回答2:


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();
}


来源:https://stackoverflow.com/questions/16544976/how-to-suspend-javascript-to-allow-render

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!