javascript - 读取文件时行之间的延迟[错误]
问题描述
我有以下代码逐行读取文件的内容。
document.getElementById('file').onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent) {
var fileContentArray = this.result.split(/\r\n|\n/);
for (var line = 0; line < fileContentArray.length - 1; line++) {
console.log(line + " --> " + fileContentArray[line]);
}
};
reader.readAsText(file);
};
我知道延迟 JS 的代码是
setTimeout(function() {
}, 1000)
我想逐行显示,但行之间有 1 秒的延迟
但我已经把它放在 for 循环之前,它不起作用。
解决方案
您可以使用setInterval
在间隔内执行您的功能。
也别忘了clearInterval
什么时候条件满足,否则函数会不停
示例代码
document.getElementById('file').onchange = function () {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function (progressEvent) {
var fileContentArray = this.result.split(/\r\n|\n/);
let index = 0;
const interval = setInterval(function() {
console.log(index + " --> " + fileContentArray[index]);
++index;
if (index === lines.length) {
clearInterval(interval);
}
}, 1000)
};
reader.readAsText(file);
};
推荐阅读
- sql-server - Microsoft SQL Server Management Studio - 添加新链接服务器时无法选择“其他数据源”
- assembly - 如何正确获取 VBE 数据?int 10h/ax=4F
- c# - 无法在我的简单 xamarin 聊天应用程序中连接到 ASP.NET Core SignalR
- excel - 从目录和子目录中获取过滤后的文件名列表到数组中
- mysql - MariaDB 存储过程选择语句仅返回单行
- go - “make fmt”如何生成 thrift 文件?
- c++ - ifstream 其他行中的不同数据类型
- python-3.x - 球体 PI 的近似值
- fiddler - 我们可以加快转储命令吗?
- android - 如果使用功能传递路径,则未找到 ChromeDrivers 异常 - chromedriverExecutableDir