Skip to content

Visualize Your Ideas With Code

feat(core): thread pausing (#639)

Jacobc0aab588b18c
diff --git a/packages/core/src/threading/Thread.ts b/packages/core/src/threading/Thread.ts
index c1a0c595..b484ef42 100644
--- a/packages/core/src/threading/Thread.ts
+++ b/packages/core/src/threading/Thread.ts
@@ -47,8 +47,13 @@ export class Thread {
return this.isCanceled || (this.parent?.canceled ?? false);
}
+ public get paused(): boolean {
+ return this.isPaused || (this.parent?.paused ?? false);
+ }
+
public parent: Thread | null = null;
private isCanceled = false;
+ private isPaused = false;
private fixedTime = 0;
public constructor(
@@ -62,6 +67,13 @@ export class Thread {
* Progress the wrapped generator once.
*/
public next() {
+ if (this.paused) {
+ return {
+ value: null,
+ done: false,
+ };
+ }
+
startThread(this);
const result = this.runner.next(this.value);
endThread(this);
@@ -75,8 +87,10 @@ export class Thread {
* @param dt - The delta time of the next cycle.
*/
public update(dt: number) {
- this.time(this.time() + dt);
- this.fixedTime += dt;
+ if (!this.paused) {
+ this.time(this.time() + dt);
+ this.fixedTime += dt;
+ }
this.children = this.children.filter(child => !child.canceled);
}
@@ -95,4 +109,8 @@ export class Thread {
this.isCanceled = true;
this.parent = null;
}
+
+ public pause(value: boolean) {
+ this.isPaused = value;
+ }
}
diff --git a/packages/core/src/threading/threads.test.ts b/packages/core/src/threading/threads.test.ts
index 35dee719..e0cd7262 100644
--- a/packages/core/src/threading/threads.test.ts
+++ b/packages/core/src/threading/threads.test.ts
@@ -1,7 +1,7 @@
import {describe, test, expect, beforeAll, afterAll} from 'vitest';
import {threads} from './threads';
import {noop, run} from '../flow';
-import {endPlayback, startPlayback} from '../utils';
+import {endPlayback, startPlayback, useThread} from '../utils';
import {PlaybackManager, PlaybackStatus} from '../app';
describe('threads()', () => {
@@ -43,4 +43,30 @@ describe('threads()', () => {
expect([...task].length).toBe(2);
});
+
+ test('Pausing a thread', () => {
+ const order: number[] = [];
+ const task = threads(function* () {
+ order.push(0);
+ yield run(function* () {
+ order.push(1);
+ yield;
+ order.push(5);
+ });
+ const child = useThread().children[0];
+ child.pause(true);
+ order.push(2);
+ yield;
+ order.push(3);
+ yield;
+ child.pause(false);
+ order.push(4);
+ yield;
+ order.push(6);
+ });
+
+ [...task];
+
+ expect(order).toEqual([0, 1, 2, 3, 4, 5, 6]);
+ });
});