Skip to content

Instantly share code, notes, and snippets.

@jwalsh
Last active December 16, 2015 19:28
Show Gist options
  • Save jwalsh/5484886 to your computer and use it in GitHub Desktop.
Save jwalsh/5484886 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>timeout</title>
</head>
<body>
<h1>Timeout JavaScript</h1>
<p>Expect: You should see a 2s request timeout.</p>
<script src="msft-timeout.js"></script>
</body>
</html>
// Purpose: Prevent a tag request from taking more than .5s.
// Workflow for timeout state
// script msft-timeout.js:13
// 9 bk_monitor msft-timeout.js:21
// bk_timeout msft-timeout.js:29
// bkContinue
// Add a script request with an onload
window.bk_loaded = false;
window.bk_started = new Date();
var body = document.getElementsByTagName('body')[0];
function report(s) {
var _ = document.createElement('pre');
_.innerHTML = s;
body.appendChild(_);
}
function bkLoaded(n) {
report('bkLoaded' + n);
// The interval / timeout clearing could be moved here
window.bk_loaded = true;
}
// This is the base implementation of the JS tag
report('script started');
// var script ='http://tags.bluekai.com/site/14445?ret=js';
// http://www.quirksmode.org/js/placejs.html
var loaders = ['']; // 'async', 'defer',
for (var l = 0; l < loaders.length; l++) {
var n = loaders[l];
var script = 'http://wal.sh/poc/fb-perf/2s-sleep-js.php?loader=' + n;
document.write('<h2>' + n + ' ' + (new Date()).getTime() + '</h2>');
document.write('<scr'+ 'ipt id=\"bkscript' + n + '\" onload=\"bkLoaded(' + n + ')\" src=\"' + script + '\"></script>');
document.write('<h2>' + n + ' ' + (new Date()).getTime() + '</h2>');
}
// Monitor for the completion of bk_loaded
var bk_monitor = window.setInterval(function() {
report('bk_monitor');
if (bk_loaded) {
bkContinue();
}
}, 50);
// Stop monitoring and continue
var bk_timeout = window.setTimeout(function() {
report('bk_timeout');
// Set up default values or error notes
var bk_results = {
'campaigns': [
]
};
bkContinue();
}, 500);
// This won't work: once added to the DOM it will be downloaded; the
// better option is to use XHR
// http://www.nczonline.net/blog/2009/06/23/loading-javascript-without-blocking/jav
function removeScript(id) {
s = document.getElementById('bkscript');
console.log(s.src);
s.src = 'http://tags.wal.sh/';
console.log(s.src);
s.onload = function(e) {
console.log(e);
alert(id + ' loaded');
}
s.onerror = function(e) {
console.log(e);
alert(id + ' error');
}
s.parentNode.removeChild(s);
report(id + ' killed');
}
// Assume bkContinue is functionality that has a synchronous
// dependency on the tag
var bkContinue = function() {
report('bkContinue ' + (new Date() - bk_started));
// Stop monitoring
clearInterval(bk_monitor);
// Remove the timeout monitoring if the load doesn't finish
clearTimeout(bk_timeout);
// Kill the script
removeScript('bkscript');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment