axevj axevj - 1 year ago 74
Javascript Question

JavaScript - Updating variables to changing file content continuously

I am currently writing a program that reads a file input from the user, in which its contents will be changing in real time. My problem is that I can't seem to find a way to update the content continuously without having to refresh the page manually or re-upload the file. I am wondering if it is possible and if so, how I can do this.

What I attempted was to put a

setInterval
timer loop that will continuously call the
printFile
function, but it doesn't work.

var data;

$(document).ready(function() {
if (isAPIAvailable()) {
$('#files').bind('change', handleFileSelect);
}
});


function isAPIAvailable() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
return true;
} else {
//...
return false;
}
}


function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
for (var i = 0; i < files.length; i++) {
var file = files[i];
// read the file contents
setInterval(printTable(file), 10000);
}
}

function printTable(file, callback) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var csv = event.target.result;
data = $.csv.toArrays(csv);
console.log(data);
};
reader.onerror = function() {
alert('Unable to read ' + file.fileName);
};
}


I just started working with JavaScript and Web Development, so I would greatly appreciate any help or suggestions. Thanks.

Answer Source

I think you must pass function object to setInterval. The way of setInterval call is wrong.

you could try following.

setInterval(printTable, 10000, file)

Following url is documentation about setInterval.

https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download