Last active
December 25, 2015 14:19
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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