Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
⚡️ Remove artificial 4ms
nextTick()
delay when running in a browser
Fixes #646 ShareDB makes heavy use of [`nextTick()`][1]. It notably calls it every time we [send a message over a `StreamSocket`][2]. If ShareDB is running both `Backend` and `Client` in a browser (eg in client tests), `nextTick()` will [fall back to `setTimeout()`][3]. However, according to the [HTML standard][4]: > Timers can be nested; after five such nested timers, however, the > interval is forced to be at least four milliseconds. So using `setTimeout()` can incur a penalty of 4ms in the browser, just idling. Over the course of a test suite, which makes a lot of fast ShareDB requests in series, these delays can add up to many seconds or even minutes of idle CPU time. This change adds an alternative `nextTick()` implementation, using `MessageChannel`, which is present in both [Node.js][5] and [HTML][6] (with slightly different APIs, but close enough for our purposes). This class offers a way of waiting for a tick on the event loop, without the arbitrary 4ms delay. `MessageChannel` is [supported back to even IE10][7], and since Node.js v10.5.0, but if for some reason it's missing, we'll still fall back to `setTimeout()`. [1]: https://github.com/share/sharedb/blob/5259d0e0b66c50ff9e745fe34a55c5fb16c57a8e/lib/util.js#L88 [2]: https://github.com/share/sharedb/blob/5259d0e0b66c50ff9e745fe34a55c5fb16c57a8e/lib/stream-socket.js#L58 [3]: https://github.com/share/sharedb/blob/5259d0e0b66c50ff9e745fe34a55c5fb16c57a8e/lib/util.js#L98 [4]: https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers [5]: https://nodejs.org/api/worker_threads.html#class-messagechannel [6]: https://html.spec.whatwg.org/multipage/web-messaging.html#message-channels [7]: https://caniuse.com/mdn-api_messagechannel_messagechannel
- Loading branch information