Given the black-box1 nature of Web Workers2, it can seem difficult to get an accurate assessment of where exactly time is being spent.
Most modern browsers support the high resolution time API via performance.now(). This method gives you micro-second precision performance information, and it is a great way to keep an eye on application performance.
For those browsers that don’t yet support high resolution time, I created a simple 0.1 kb performance.now polyfill a couple years ago.
Until today the polyfill worked great in a browser context but threw an error if you tried to use the script in a Web Worker. This was because the script assumed it would be augmenting the window object.
Simply changing window to self was all it took to make the perfnow.js micro-library compatible with web workers!
Web Worker Example
Following is a simple example of how you can use the polyfill in your projects.
Example HTML Markup
Both the example and the worker are available on CodePen if you want to see them in action.
Note: As a general rule, if a browser supports Web Workers it also supports performance.now() natively, with iOS Safari version 8.4 being a notable exception to that rule. Therefore, this polyfill is probably most useful outside the context of web workers.
A “black box” system is where you only have access to the input and output information without insight into how it is processed. ↩