What does the 'Separately Do' block do in the Timer Extension?

Screenshot 2024-06-20 at 9.30.47 pm
I’m wondering because it would be really helpful if it could run two chunks of code at the same time.

1 Like

makecode supports multiple threads, and as you correctly guessed the separately do block is for spawning another thread! however, there are some things to understand about threading in makecode before you get too excited.

only one thread ever runs at a time in makecode. in other words, there is only one virtual “cpu” for you to use. we have a scheduler which decides which thread is the one that is currently running and that thread will run uninterrupted until it cedes control to another thread. this is called “non-preemptive multithreading”.

so, how does one thread cede control back to the scheduler? well, any block in makecode that pauses for some amount of time will also give up control! that includes the pause and pause until blocks, but also other blocks that use pause under the hood like playing a sound with the “until done” option or the forever block.

alright, I know that was a lot of jargon so let’s take a look at some examples!

Example 1: thread with no pause

in this program, we create a sprite and have a for-loop that runs 10,000 iterations. each time the for-loop runs, our sprite should say the value of the current index:

you might expect this program to display all the numbers between 0 and 10,000, but when we run it we actually only see the last number:

threading-no-pause

that’s because our for-loop never calls pause; this thread will keep running until all 10,000 iterations are complete before it ends and lets the game engine’s thread draw to the screen

Example 2: thread with a pause

let’s rewrite the program from example 1 with a pause inside the loop:

even though we’re pausing for 0 ms, this will still cause the thread to give up control to the game engine thread so that the screen can be redrawn. running this program we now get the desired result:

threading-pause

you might also notice that this program runs way, way slower than the other one! that’s because pausing, even for 0 ms, always takes time.

if we were doing something time intensive in this thread, it would probably be smarter to make it pause once every 100 iterations or something, but i’ll leave that as an exercise for you!

4 Likes

Alright, thank you for the explanation!

WOW! Immensely useful info!

1 Like

i’m going to do a full “richard’s arcade tips” on this so stay tuned

7 Likes

OOOOOHH

1 Like

i used it for stuff like cutscenes