Skip to content

Commit ac5f8dc

Browse files
zenflowkitten
andauthored
Disable setImmediate event loop yielding in the browser, (#50)
* Disable `setImmediate` event loop yielding in the browser, Closes #48 * Apply suggestions from code review Co-Authored-By: Phil Plückthun <phil@kitten.sh> * Disable yielding in `visitLoop` in environments with no `setImmediate` Co-authored-by: Phil Plückthun <phil@kitten.sh>
1 parent 152bf07 commit ac5f8dc

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

src/index.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import React, { type Node, type Element } from 'react'
44
import type { Visitor, YieldFrame, Frame, AbstractElement } from './types'
5-
import { visitChildren, resumeVisitChildren, update } from './visitor'
5+
import { visitChildren, resumeVisitChildren, update, SHOULD_YIELD } from './visitor'
66
import { getChildrenArray } from './element'
77

88
import {
@@ -51,14 +51,19 @@ const updateWithFrame = (
5151
): Promise<void> => {
5252
if (frame.kind === 'frame.yield') {
5353
return new Promise((resolve, reject) => {
54-
setImmediate(() => {
54+
const resume = () => {
5555
try {
5656
resumeWithDispatcher(frame, queue, visitor)
5757
resolve()
5858
} catch (err) {
5959
reject(err)
6060
}
61-
})
61+
}
62+
if (SHOULD_YIELD) {
63+
setImmediate(resume)
64+
} else {
65+
resume()
66+
}
6267
})
6368
}
6469

src/visitor.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,11 @@ import {
6767
REACT_LAZY_TYPE
6868
} from './symbols'
6969

70+
// In the presence of setImmediate, i.e. on Node, we'll enable the
71+
// yielding behavior that gives the event loop a chance to continue
72+
// running when the prepasses would otherwise take too long
73+
export const SHOULD_YIELD = typeof setImmediate === 'function';
74+
7075
// Time in ms after which the otherwise synchronous visitor yields so that
7176
// the event loop is not interrupted for too long
7277
const YIELD_AFTER_MS = process.env.NODE_ENV !== 'production' ? 20 : 5
@@ -189,7 +194,7 @@ const visitLoop = (
189194
restoreContextStore(traversalStore.pop())
190195
}
191196

192-
if (Date.now() - start > YIELD_AFTER_MS) {
197+
if (SHOULD_YIELD && (Date.now() - start > YIELD_AFTER_MS)) {
193198
return true
194199
}
195200
}

0 commit comments

Comments
 (0)