Skip to content

Instantly share code, notes, and snippets.

@el-gringo
Last active December 25, 2015 14:19
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 el-gringo/6990785 to your computer and use it in GitHub Desktop.
Save el-gringo/6990785 to your computer and use it in GitHub Desktop.
I use the multithread HTML5 worker which will be able to abort an synchronous XMLHttpRequest pointing to an unresponsive URL. This does not block the browser.
function sleep(milliseconds) {
var xhr = new XMLHttpRequest();
// Open a non existing url
xhr.open('GET', location.protocol + '//sleep' + (new Date()).getTime(), false);
var blob = new Blob([
"onmessage = function() { setTimeout(function() {postMessage('done');}, "+milliseconds+"); }"]);
var blobURL = window.URL.createObjectURL(blob);
var worker = new Worker(blobURL);
worker.onmessage = function() {
xhr.abort();
window.URL.revokeObjectURL(blobURL);
};
worker.postMessage('sleep');
xhr.send(null);
};
var start = new Date().getTime();
sleep(2000);
var end = new Date().getTime();
console.log('time: ' + (end - start));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment