使用下面的代码,我正在读取.csv文件:
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]);
我的目标是在读取文件时每2秒调用一次方法sendToDatabase()
。换句话说,在读取文档的一行之后,调用该方法并等待2秒钟,然后再读取下一行。
在主题setTimeout in for-loop does not print consecutive values的帮助下,我正在玩setTimeout()
,但始终没有我需要的东西……可能我错过了一些东西……
答案 0 :(得分:2)
由于您要定期执行某项操作,因此应使用setInterval()
。在循环函数中增加数组索引,而不是循环。
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]);
答案 1 :(得分:0)
我相信这可以工作:
for(....) {
.
.
.
(function(student_info) {
sendToDatabase(student_info);
})(a_student_info);
}