首页 > 解决方案 > 读取文件时行之间的延迟[错误]

问题描述

我有以下代码逐行读取文件的内容。

 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 循环之前,它不起作用。

标签: javascript

解决方案


您可以使用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);
};

推荐阅读