Effect of fast timers on setTimeout

This test demonstrates the effect of a browser's minimum setTimeout time on the browser.

In this visual depiction of the QuickSort algorithm, each step of the sort yields to the browser to allow the browser to update the UI.

In the first test, the value passed to setTimeout is 0ms.
In the second test, the value passed to setTimeout is 10ms.
Aside from the value passed to setTimeout, these two tests are identical.

To run the test

  1. Click the Start Button:
  2. Let the test run
  3. Note the "Sort Time" recorded in the upper right corner of each graph (smaller is better).

Expected Results

  • Browsers which clamp the minimum setTimeout interval should demonstrate no perceptible difference between the two tests.
  • Browsers which allow sub-millisecond timing should demonstrate considerable speed increases with the 0ms test.

    Size
    * Thanks to Erik Kay for writing this sort test.

    Summary and Alternatives

    If you run this test in browsers without setTimeout clamps, you'll see that the first test runs 3-5 times faster than the second. (e.g. Chrome)

    If you run this test in browsers which clamp setTimeout, both tests will run comparably and slowly. (e.g. IE, Firefox, Safari).

    The reason for the difference in time is that the work done in each "step" is far smaller than the setInterval() minimum threshold.

    Now, there there is a workaround to make this test run quickly in all browsers; the key is to better saturate the CPU. To do this, the application writer could do more than one "step" of work inside the loop before 'yielding' back to the browser. This would allow the application to run quickly regardless of the browser's minimum setTimeout interval.

    There are three problems with this approach: