Reputation: 2060
With code below I am reading .csv file:
var fileInput = document.getElementById("uploaded-file");
var reader = new FileReader();
reader.onload = function () {
var students_data = reader.result.split(/\r?\n|\r/);
for(var count = 1; count<students_data.length; count++){
var str_students_information = students_data[count];
var arr_students_information = str_students_information.split(',');
var a_student_info = [
{name: 'student', value: 'add-student'},
{name:"id",value:arr_students_information[0]},
{name:"name",value:arr_students_information[1]},
{name:"mname",value:arr_students_information[2]},
{name:"sname",value:arr_students_information[3]}
];
sendToDatabase(a_student_info);
}
};
reader.readAsBinaryString(fileInput.files[0]);
My goal to achieve is to call method sendToDatabase()
every 2 seconds while reading a file. Another way to say, after a line of a document was read call the method and wait 2 seconds before reading next line.
With help of topic setTimeout in for-loop does not print consecutive values I was playing with setTimeout()
, but always have not what I need...Probably I am missing something...
Upvotes: 1
Views: 1049
Reputation: 781721
Since you want to do something periodically, you should use setInterval()
. Instead of a loop, you increment the array index in the callback function.
var fileInput = document.getElementById("uploaded-file");
var reader = new FileReader();
reader.onload = function() {
var students_data = reader.result.split(/\r?\n|\r/);
var count = 1;
var interval = setInterval(function() {
if (count >= students_data.length) {
clearInterval(interval);
return;
}
var str_students_information = students_data[count];
var arr_students_information = str_students_information.split(',');
var a_student_info = [{
{name: 'student', value: 'add-student'},
{name:"id",value:arr_students_information[0]},
{name:"name",value:arr_students_information[1]},
{name:"mname",value:arr_students_information[2]},
{name:"sname",value:arr_students_information[3]}
];
sendToDatabase(a_student_info);
count++;
}, 2000);
};
reader.readAsBinaryString(fileInput.files[0]);
Upvotes: 2
Reputation: 518
I belive this can works:
for(....) {
.
.
.
(function(student_info) {
sendToDatabase(student_info);
})(a_student_info);
}
Upvotes: 0