Skip to content

Instantly share code, notes, and snippets.

@benjamincharity
Created September 26, 2019 14:49
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 benjamincharity/0472b74cac9b7a812836fa64e174d928 to your computer and use it in GitHub Desktop.
Save benjamincharity/0472b74cac9b7a812836fa64e174d928 to your computer and use it in GitHub Desktop.
<!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