public
Last active

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.

  • Download Gist
sleep.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
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));

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.