Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p>Will take ~5 seconds from the time of click to simulate async generation:</p>
<button id="foo">Click me!</button>
</body>
</html>
var time;
var btn = document.getElementById('foo');
var interval;
// set up object to allow listening for variable changes
var x = {
aInternal: false,
aListener: function (val) {},
set a(val) {
this.aInternal = val;
this.aListener(val);
},
get a() {
return this.aInternal;
},
registerListener: function (listener) {
this.aListener = listener;
},
unRegisterListener: function () {
this.aListener = undefined;
},
}
// listen for button click
btn.addEventListener('click', (e) => {
console.log('Clicked!');
time = new Date().getTime();
}, false);
// listen for a variable change caused by the server
x.registerListener(function (val) {
x.unRegisterListener();
clearInterval(interval);
download('testing', 'http://bnj.bz/b60449/CSV%252520Test%252520File.csv');
});
// trigger the actual download
function download(filename, link) {
var element = document.createElement('a');
element.setAttribute('href', link);
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
console.log('Triggering download!');
element.click();
document.body.removeChild(element);
}
// simulate the server saying 'file done' at some point
function maybeChangeFlag() {
var newTime = new Date().getTime();
if (time) {
console.log('time passed: ', newTime - time);
}
if (time && newTime - time > 5000) {
console.log('Server set flag!');
x.a = true;
}
}
// start the interval now so the button click isn't tied to it
interval = setInterval(maybeChangeFlag, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.