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);