Error: Pause in line progression when processing file [ERROR]

Below is a snippet of code that allows for the reading of file content line by line.

 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);
};

In JavaScript, delaying execution can be achieved using:

setTimeout(function() { 
}, 1000)

The goal here is to display each line with a one-second delay between them.

However, attempts to integrate the delay before the for loop have been unsuccessful.

Answer №1

If you want to run your function at regular intervals, you can utilize the setInterval method.

Remember to use clearInterval once the specified condition is met to avoid an endless loop.

Here's a sample code snippet:

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);
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When the li is clicked, replicate it and display it in a separate div

When a list item is clicked, I want to clone it and display it in a separate div. If another list item is clicked, the previously displayed item should be replaced with the newly clicked one. Below is my code along with a link to the codepen where you can ...

Custom options in MUI Autocomplete are not displaying the selected option

I am currently implementing MUI v5's Autocomplete for a dropdown feature on my website. Within this dropdown, I have options that include both a title and an id. My goal is to store the selected option's id in the state while also updating the d ...

apply white-space:nowrap to a single column in a datatable

I am facing a challenge with my bootstrap datatable where one row (Product) contains a large amount of data and currently expands downwards, taking up a lot of space. https://i.sstatic.net/BryzM.png My goal is to make the Product column expand to the rig ...

Unable to assign a value to an indexed property in 'FileList': Setter function for index properties is not enabled

angular.module('myApp') .directive('fileModel', ['$parse', 'uploadService','messageService','CONF', function ($parse, uploadService,messageService,CONF) { return { restrict ...

What is the correct way to use "DELETE" and "BACKSPACE" in a condition statement?

Attempting to prevent the deletion of input values when the length is 2 or lower, but my if statement doesn't seem quite right. $(document).ready(function() { $('#mobile').val("09"); // Set initial value to "09" $('#mobile&ap ...

Best practices for loading and invoking Javascript in WordPress child themes

After spending countless hours searching for a detailed tutorial on how to properly incorporate Javascript into a WordPress website, I came up empty-handed. Running the Genesis Framework with a child theme on my localhost, I am eager to add a fullscreen b ...

Is it necessary for a component to disconnect from the socket io server upon unmounting?

Is it best practice for a React component to automatically disconnect from a socket.io server when it unmounts using the useEffect hook? If so, could you provide an example of the syntax for disconnecting a React component from a socket.io server? ...

What is the best way to store types in a TypeScript-based React/Next application?

I'm currently in the process of setting up a Next.js page in the following manner const Index: NextPage<PageProps> = (props) => { // additional code... Prior to this, I had defined my PageProps as follows: type PageProps = { pictures: pi ...

Error message: The Javascript Electron app is unable to find the node-fetch module when

Below is the code snippet from my gate.html file: <html> <head> <meta http-equiv='Content-Security-Policy' content='default-src 'self'; https://example.com.tr/validkeys.txt'> <meta http-equiv=&ap ...

What is the best way to save the content of an RFC822 message body as a String?

let inbox = require("inbox"); let client = inbox.createConnection(false, "imap.gmail.com", { secureConnection: true, auth:{ user: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99f4e0fcf4f8f0f5d9fef4f8f0f5b7fa ...

I require a breakdown of the JavaScript code, please

Are you struggling with a code snippet that involves CSS, JavaScript, and HTML? Let's take a look at the complete code: <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="http://snipplicious.com/css/bo ...

Utilizing dynamic content to pass arguments to JavaScript functions

I'm facing a challenging issue that is causing me frustration. While browsing through this platform, I found some potential solutions but encountered a roadblock in implementing them successfully. My current project involves developing an e-commerce p ...

Issue with event.stopPropagation() in Angular 6 directive when using a template-driven form that already takes event.data

I am currently developing a citizenNumber component for use in forms. This component implements ControlValueAccessor to work with ngModel. export class CitizenNumberComponent implements ControlValueAccessor { private _value: string; @Input() place ...

Issues with Rock Paper Scissors Array in Discord.js V12 not functioning as expected

I'm currently working on implementing an RPS game in my Discord bot. I want to create a feature where if the choice made by the user doesn't match any of the options in the list, it will display an error message. Here is the code snippet that I h ...

Finally, $.getJSON has been triggered

When I click on an element, I want to open a bootstrap modal. The modal contains values retrieved from an ajax call using getJSON. However, the issue is that the getJSON function is only called after the jQuery function has finished executing. Below is my ...

The directive 'templateUrl' points to the route '/'

I'm having an issue with using the templateUrl in a directive to load a partial. Whenever I try to visit the URL for the template, it redirects me back to /. This results in the partial loading the entire page instead of just the requested partial. a ...

Utilizing const as the iteration variable in a for loop

I've grasped the concept of using var and let in a for loop in typescript/javascript, but can someone shed light on how and why a const variable as a loop variable behaves? for (const i = 0; i < 5; i++) { setTimeout(function() { console.log( ...

Expanding upon passing arguments in JavaScript

function NewModel(client, collection) { this.client = client; this.collection = collection; }; NewModel.prototype = { constructor: NewModel, connectClient: function(callback) { this.client.open(callback); }, getSpecificCollection: ...

What causes the difference between object[key] and Object.key in JavaScript?

After running the following code snippet, I observed that "typeof object[key]" is displaying as a number while "typeof object.key" is showing undefined. Can anyone explain why this unusual behavior is occurring? var object = {a:3,b:4}; for (var key in o ...

Is the RouterModule exclusively necessary for route declarations?

The Angular Material Documentation center's component-category-list imports the RouterModule, yet it does not define any routes or reexport the RouterModule. Is there a necessity for importing the RouterModule in this scenario? ...