When you are inside a JavaScript function and want to update the canvas element then the update takes place only when the function returns. Sometimes one wishes to update the canvas and keep the function running. Is there a way to accomplish this?
Asked
Active
Viewed 70 times
0
-
1This question is very broad. Can you please post your code so that we can fix it? – Wais Kamal Feb 27 '17 at 17:49
-
@WaisKamal It's not about code, I want to know if there is a solution in general. That's why it is a bit broad. – mrk Feb 27 '17 at 18:04
-
1Use a generator function. They provide a means of creating interruptible execution. Yield statements define break points and a second controlling timed animation frame loop can control progress from yield to yield statement by calling next on the provided iteration object. This answer show how it is done to visualize the steps of an algorithm. http://stackoverflow.com/a/40741857/3877726 – Blindman67 Feb 28 '17 at 02:07
-
@Blindman67 Thank you. Turn this comment into an answer and I will mark it as best answer. – mrk Feb 28 '17 at 13:32
1 Answers
1
In general: no, there is no straightforward way to do that, because the browser blocks every ui event until its scripting routines have terminated. This includes updating the canvas (and even closing the browser window e.g. when a script gets to an infinite loop, you may have seen that somewhere before).
Anyway, a more or less ugly way to do this, is using a setTimeout at the point where you want your canvas to be updated:
function reactOnSomething(){
doSomeStuff();
drawMyCanvas();
setTimeout(function(){
goOnWithOtherStuff();
}, 20);
}

Psi
- 6,387
- 3
- 16
- 26