Skip to content

Instantly share code, notes, and snippets.

@tav
Created March 23, 2014 04:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tav/9719011 to your computer and use it in GitHub Desktop.
Save tav/9719011 to your computer and use it in GitHub Desktop.
<!doctype html>
<meta charset=utf-8>
<title>setImmediate alternatives</title>
<style>
table td {
padding: 20px;
}
.unavailable {
text-decoration: line-through;
}
</style>
<body>
<h1>setImmediate alternatives</h1>
<blockquote><table id="listing"></table></blockquote>
<script>
root = this;
impls = {}
setImpl = function(name, impl, call) {
if (typeof root[name] !== 'undefined') {
if (call) {
impl = impl();
}
impls[name] = impl;
} else {
impls[name] = false;
}
}
// Old school
setImpl('setTimeout', function(cb) {
setTimeout(cb, 0);
});
setImpl('MessageChannel', function() {
var next = void 0;
var chan = new MessageChannel();
chan.port1.onmessage = function() {
var cb = next;
next = void 0;
cb();
};
return function(cb) {
next = cb;
chan.port2.postMessage(null);
};
}, true);
setImpl('MutationObserver', function() {
var next = void 0;
var div = document.createElement("div");
var observer = new MutationObserver(function() {
var cb = next;
next = void 0;
cb();
});
observer.observe(div, {attributes: true});
return function(cb) {
next = cb;
div.setAttribute("class", "tick");
};
}, true);
key = "sched-" + Math.random();
setImpl('postMessage', function() {
var next = void 0;
addEventListener("message", function(e) {
if (e.source === root && e.data === key) {
var cb = next;
next = void 0;
cb();
}
}, false);
return function(cb) {
next = cb;
postMessage(key, "*");
};
}, true);
handleClick = function(name, $results) {
return function() {
$results.innerHTML = "Running ..."
var i = 0;
var schedule = impls[name];
var start = Date.now();
var cb = function() {
if (i == 1000) {
$results.innerHTML = Date.now() - start;
} else {
i += 1
schedule(cb);
}
}
cb();
}
}
implNames = Object.keys(impls);
implNames.sort();
$listing = document.getElementById('listing');
implNames.map(function(name) {
var $tr = document.createElement('tr')
var $runner = document.createElement('td')
var $results = document.createElement('td')
var impl = impls[name];
$runner.style.textAlign = 'right';
if (impl) {
var $button = document.createElement('button')
$button.innerHTML = name;
$button.onclick = handleClick(name, $results);
$runner.appendChild($button);
} else {
$runner.innerHTML = '<div class="unavailable">' + name + '</div>';
}
$tr.appendChild($runner);
$tr.appendChild($results);
$listing.appendChild($tr);
});
</script>
@tav
Copy link
Author

tav commented Mar 23, 2014

Results on OS X Mavericks:

* Chrome 33 Firefox 28 Safari 7
setTimeout 4634 4656 4522
MutationObserver 3 7 2
MessageChannel 144 - 4
postMessage 70 133 48

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment