Smallest timeout value (v2)

Revision 2 of this benchmark created by Thomas Aylott on


Description

The smallest setTimeout timeout value allowed by the HTML5 specification is 4 ms. Smaller values should clamp to 4 ms.

Therefore, the first two tests below should have about the same result.

Preparation HTML

<script>
  var img = new Image;
  
  
  
  (function() {
  
  var img = new Image;
  var timeouts = [];
  var SRC = 'data:image/png;base64,';
  
  // Like setTimeout, but only takes a function argument.  There's
  // no time argument (always zero) and no arguments (you have to
  // use a closure).
  function setZeroTimeoutWithImage(fn) {
      timeouts.push(fn);
      img.src = SRC;
  }
  
  function handleMessage(event) {
      event.stopPropagation();
      if (timeouts.length > 0) timeouts.shift()();
  }
  
  img.onReadyStateChange =
  img.onabort =
  img.onload =
  img.onerror =
  handleMessage;
  
  // Add the one thing we want added to the window object.
  window.setZeroTimeoutWithImage = setZeroTimeoutWithImage;
  
  })();
  
  
      // Only add setZeroTimeout to the window object, and hide everything
      // else in a closure.
      (function() {
          var timeouts = [];
          var messageName = "zero-timeout-message";
  
          // Like setTimeout, but only takes a function argument.  There's
          // no time argument (always zero) and no arguments (you have to
          // use a closure).
          function setZeroTimeout(fn) {
              timeouts.push(fn);
              window.postMessage(messageName, "*");
          }
  
          function handleMessage(event) {
              if (event.source == window && event.data == messageName) {
                  event.stopPropagation();
                  if (timeouts.length > 0) {
                      var fn = timeouts.shift();
                      fn();
                  }
              }
          }
  
          window.addEventListener("message", handleMessage, true);
  
          // Add the one thing we want added to the window object.
          window.setZeroTimeout = setZeroTimeout;
      })();
  
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
timeout = 0
// async test
setTimeout(function() {
  deferred.resolve();
}, 0);
ready
timeout = 4
// async test
setTimeout(function() {
  deferred.resolve();
}, 4);
ready
timeout = 10
// async test
setTimeout(function() {
  deferred.resolve();
}, 10);
ready
timeout = 40
// async test
setTimeout(function() {
  deferred.resolve();
}, 40);
ready
setZeroTimeout
// async test
setZeroTimeout(function() {
  deferred.resolve();
})
 
ready
Image.onerror
// async test
img.onload = img.onerror = function() {
  deferred.resolve()
  return true
};
img.src = 'data:image/png;base64,';
 
ready
setZeroTimeoutWithImage
// async test
setZeroTimeoutWithImage(function() {
  deferred.resolve();
})
 
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.