Last active
September 9, 2025 05:27
-
-
Save Ctrlmonster/e104198d66170957aa3bf86c28a32ee8 to your computer and use it in GitHub Desktop.
higher frequency setTimeout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Copy paste these into your console to compare: | |
| // ============================================================================ | |
| // setTimeout | |
| // ============================================================================ | |
| // Measures time between back-to-back setTimeout(..., 0) callbacks | |
| (function setTimeoutDiffTest(iterations = 200) { | |
| let last = performance.now(); | |
| let i = 0; | |
| function tick() { | |
| const now = performance.now(); | |
| if (i > 0) console.log(`#${i}: ${(now - last).toFixed(3)} ms`); | |
| last = now; | |
| i++; | |
| if (i <= iterations) setTimeout(tick, 0); | |
| } | |
| setTimeout(tick, 0); // <- in chrome this will cap at ~4ms after 5 calls | |
| })(); | |
| // ============================================================================ | |
| // postMessage pinging | |
| // ============================================================================ | |
| // Ping-pong postMessage RTT test using an inline Worker (via Blob) | |
| (function postMessageRTTTest(iterations = 200) { | |
| const workerSrc = ` | |
| // Echo back immediately with the same id (pong) | |
| self.onmessage = (e) => { self.postMessage(e.data); }; | |
| `; | |
| const blob = new Blob([workerSrc], { type: "application/javascript" }); | |
| const url = URL.createObjectURL(blob); | |
| const worker = new Worker(url); | |
| let i = 0; | |
| const sentAt = []; | |
| worker.onmessage = (e) => { | |
| const { id } = e.data || {}; | |
| const start = sentAt[id]; | |
| if (start !== undefined) { | |
| const dt = performance.now() - start; | |
| console.log(`#${id}: ${dt.toFixed(3)} ms`); | |
| sentAt[id] = undefined; | |
| } | |
| if (i < iterations) { | |
| ping(); | |
| } else { | |
| worker.terminate(); | |
| URL.revokeObjectURL(url); | |
| } | |
| }; | |
| function ping() { | |
| i += 1; | |
| sentAt[i] = performance.now(); | |
| // if you need to throttle the timouts (which a real app | |
| // likely will as this takes a lot of CPU usage), you can do | |
| // a setTimeout(_, 1) here | |
| worker.postMessage({ id: i }); | |
| } | |
| // Kick off the first ping | |
| ping(); | |
| })(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment