The default behaviour is for the print block, in blockly, to output print statements in an alert() and outputs are outputted immediately after the block is executed and before the rest of the blocks (in a stack) are executed.
In trying to make the outputs display in a div I made the following alterations:
Blockly.JavaScript['text_print'] = function(block) {
var msg = Blockly.JavaScript.valueToCode(block, 'TEXT', Blockly.JavaScript.ORDER_NONE) || '\'\'';
return 'printToOutput(' + msg + ');\n';
};
function printToOutput(text) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML += text + '<br>';
}
This does enable the code outputs to display in a div (handled by the function printToOutput). However, the behaviour now is that it will only show all outputs from print blocks after the entire code has been executed.
For example, if I have a set of blocks set up for a script that first requests a user input via the prompt (using the 'prompt for text with message' block), stores it in a variable, outputs this variable (with a print block), then requests a second input via the prompt (using the 'prompt for text with message' block), storing it in a different variable and then outputting it to the screen, the outputs from the 'print' blocks are only shown once the entire script block has finished executing. What i would have hoped for (and what I need) is that the first output is displayed to the user before the second user input is requested.
How can I ensure that outputs from print blocks can be displayed in the div, during code execution and not afterwards?
EDIT:
So, with some more experimenting and research I realise that what happens is that the JS code generated from the blocks, is passed to eval()
for execution. But when executing lines such as div.innerHTML += "some text";
the DOM doesn't update in real time execution of the code and will only update when the code execution is complete.
Therefore, how can I ensure that lines such as div.innerHTML += "some text";
will update the DOM immediately and before the rest of the JS code has executed?
I've looked at splitting the code and trying to run each line with an await/promise, but the issue is that the code may have a single executable line of code over several lines, so chopping by \n, or even by curly brackets or colons is not so simple and I probably won't capture every possibility.
So what might be the best solution?