From d161251a9b6acc45a36f5991b91ba80abd9d22d1 Mon Sep 17 00:00:00 2001
From: "Michael \"Z\" Goddard" <mzgoddard@gmail.com>
Date: Wed, 6 Jun 2018 09:59:38 -0400
Subject: [PATCH] yield a thread loop or tick in event_broadcastandwait

- yield a thread loop or tick in looks_switchbackdroptoandwait

If all threads broadcastAndWait is watching are "waiting" for a future
frame, yield until the next tick so event_broadcastandwait also defers
to a future frame.
---
 src/blocks/scratch3_event.js | 12 +++++++++++-
 src/blocks/scratch3_looks.js | 12 +++++++++++-
 2 files changed, 22 insertions(+), 2 deletions(-)

diff --git a/src/blocks/scratch3_event.js b/src/blocks/scratch3_event.js
index ba496a172..6d4eaca8a 100644
--- a/src/blocks/scratch3_event.js
+++ b/src/blocks/scratch3_event.js
@@ -100,7 +100,17 @@ class Scratch3EventBlocks {
             const instance = this;
             const waiting = util.stackFrame.startedThreads.some(thread => instance.runtime.isActiveThread(thread));
             if (waiting) {
-                util.yield();
+                // If all threads are waiting for the next tick or later yield
+                // for a tick as well. Otherwise yield until the next loop of
+                // the threads.
+                if (
+                    util.stackFrame.startedThreads
+                        .every(thread => instance.runtime.isWaitingThread(thread))
+                ) {
+                    util.yieldTick();
+                } else {
+                    util.yield();
+                }
             }
         }
     }
diff --git a/src/blocks/scratch3_looks.js b/src/blocks/scratch3_looks.js
index 4a7994a4a..21599f251 100644
--- a/src/blocks/scratch3_looks.js
+++ b/src/blocks/scratch3_looks.js
@@ -409,7 +409,17 @@ class Scratch3LooksBlocks {
         const instance = this;
         const waiting = util.stackFrame.startedThreads.some(thread => instance.runtime.isActiveThread(thread));
         if (waiting) {
-            util.yield();
+            // If all threads are waiting for the next tick or later yield
+            // for a tick as well. Otherwise yield until the next loop of
+            // the threads.
+            if (
+                util.stackFrame.startedThreads
+                    .every(thread => instance.runtime.isWaitingThread(thread))
+            ) {
+                util.yieldTick();
+            } else {
+                util.yield();
+            }
         }
     }