Skip to content

Commit

Permalink
Add fake setInterval to streams/resources/rs-utils.js
Browse files Browse the repository at this point in the history
In order for tests using this resource to run properly in a ShadowRealm,
we need to make a fake setInterval()/clearInterval() if both are not
present on the global object.

See: tc39/proposal-shadowrealm#396
  • Loading branch information
ptomato committed Oct 21, 2024
1 parent 4ba09d0 commit 17cb5f2
Showing 1 changed file with 41 additions and 4 deletions.
45 changes: 41 additions & 4 deletions streams/resources/rs-utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,42 @@
'use strict';
(function () {
// Fake setInterval-like functionality in environments that don't have it
class IntervalHandle {
constructor(callback, delayMs) {
this.callback = callback;
this.delayMs = delayMs;
this.cancelled = false;
Promise.resolve().then(() => this.check());
}

async check() {
while (true) {
await new Promise(resolve => step_timeout(resolve, this.delayMs));
if (this.cancelled) {
return;
}
this.callback();
}
}

cancel() {
this.cancelled = true;
}
}

let localSetInterval, localClearInterval;
if (typeof globalThis.setInterval !== "undefined" &&
typeof globalThis.clearInterval !== "undefined") {
localSetInterval = globalThis.setInterval;
localClearInterval = globalThis.clearInterval;
} else {
localSetInterval = function setInterval(callback, delayMs) {
return new IntervalHandle(callback, delayMs);
}
localClearInterval = function clearInterval(handle) {
handle.cancel();
}
}

class RandomPushSource {
constructor(toPush) {
Expand All @@ -18,12 +55,12 @@
}

if (!this.started) {
this._intervalHandle = setInterval(writeChunk, 2);
this._intervalHandle = localSetInterval(writeChunk, 2);
this.started = true;
}

if (this.paused) {
this._intervalHandle = setInterval(writeChunk, 2);
this._intervalHandle = localSetInterval(writeChunk, 2);
this.paused = false;
}

Expand All @@ -37,7 +74,7 @@

if (source.toPush > 0 && source.pushed > source.toPush) {
if (source._intervalHandle) {
clearInterval(source._intervalHandle);
localClearInterval(source._intervalHandle);
source._intervalHandle = undefined;
}
source.closed = true;
Expand All @@ -55,7 +92,7 @@

if (this.started) {
this.paused = true;
clearInterval(this._intervalHandle);
localClearInterval(this._intervalHandle);
this._intervalHandle = undefined;
} else {
throw new Error('Can\'t pause reading an unstarted source.');
Expand Down

0 comments on commit 17cb5f2

Please sign in to comment.