JS/Electron Insert items individually

Apologies if my explanation is unclear. I have a function (shown below) that parses a JSON file and creates a grid of 1550 items. How can I add them one by one instead of all at once? Loading all 1500 items together is taking too long.

function addItem () {
  fs.readFile(path.join(__dirname, 'list.json'), 'utf8', (err, data) => {
    if (err) {
      alert('Could not read file.\n\nDetails:\n' + err.message);
      return;
    }
    let json = JSON.parse(data);
    for (let i in json) {
      mainWindow.webContents.executeJavaScript(`
        document.getElementById("grid").innerHTML += '<a href="${json[i].desc}"><div class="cell" id=${i}>${json[i].title}</div> </a>'
      `);
    }
  });
}

In the code snippet below, I create a window, display a splash screen, then show the main window. I call the function on app ready event.

function initializeApp() {
    splash = new BrowserWindow({width: 200, height: 200, transparent: true, frame: false, alwaysOnTop: true});
    (async ()=>{  
        createWindow(); 
        splash.loadFile('splash.html');  
        await sleep(2000);  
        splash.destroy();
        mainWindow.show();
        
      })();
}

app.on('ready', initializeApp);

Any help or suggestions would be greatly appreciated. Thank you!

Answer №1

Your inquiry is quite insightful, particularly in relation to async programming concepts. You may want to substitute the function with:

option A)

if the sequence of items is not crucial.

async function loop_iteration(json, i) {
    mainWindow.webContents.executeJavaScript(`
        document.getElementById("grid").innerHTML += '<a href="${json[i].desc}"><div class="cell" id=${i}>${json[i].title}</div> </a>'
      `)
}

function additem () {
  fs.readFile(path.join(__dirname, 'list.json'), 'utf8', (err, data) => {
    if (err) {
      alert('Could not read file.\n\nDetails:\n' + err.message)
      return
    }
    let json = JSON.parse(data)
    for (let i in json) {
        loop_iteration(json, i);
    }
  })
}

This ensures that each loop iteration is executed asynchronously, allowing for independent execution without waiting for prior iterations.

option B)

If maintaining the order of items is important.

The page remains responsive, but all iterations are executed simultaneously.

async function loop(json) {
    for (let i in json) {
        mainWindow.webContents.executeJavaScript(`
        document.getElementById("grid").innerHTML += '<a href="${json[i].desc}"><div class="cell" id=${i}>${json[i].title}</div> </a>'
      `)
    }
}

function additem() {
    fs.readFile(path.join(__dirname, 'list.json'), 'utf8', (err, data) => {
        if (err) {
            alert('Could not read file.\n\nDetails:\n' + err.message)
            return
        }
        let json = JSON.parse(data)
        loop(json);
    })
}

This approach makes the entire loop asynchronous, ensuring that each iteration waits for the previous one to complete, providing a smooth user experience without freezes or delays.

In order to balance both requirements effectively, consider this option:

option C)

Precisely what you had in mind.

async function loop_iteration(json, i) {
    mainWindow.webContents.executeJavaScript(`document.getElementById("grid").innerHTML += '<a href="${json[i].desc}"><div class="cell" id=${i}>${json[i].title}</div> </a>'`)
}

async function loop(json) {
    for (let i in json) {
        await loop_iteration(json, i);
    }
}

function additem() {
    fs.readFile(path.join(__dirname, 'list.json'), 'utf8', (err, data) => {
        if (err) {
            alert('Could not read file.\n\nDetails:\n' + err.message)
            return
        }
        let json = JSON.parse(data)
        loop(json);
    })
}

In this scenario, the browser is instructed to start executing each iteration only after the completion of the previous one in the loop, enhancing efficiency and performance.

Option D)

Utilizes asynchronous loading of the JSON data to render the page content once efficiently.

async function loop_iteration(json, i, arr) {
    arr.push(`<a href="${json[i].desc}"><div class="cell" id=${i}>${json[i].title}</div> </a>`)
}

async function loop(json) {
    const arr = []
    for (let i in json) {
        await loop_iteration(json, i, arr);
    }
    mainWindow.webContents.executeJavaScript(`document.getElementById("grid").innerHTML += '${arr.join('')}'`)
}


function additem() {
    fs.readFile(path.join(__dirname, 'list.json'), 'utf8', (err, data) => {
        if (err) {
            alert('Could not read file.\n\nDetails:\n' + err.message)
            return
        }
        let json = JSON.parse(data)
        loop(json);
    })
}

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

What is the best way to showcase this information within my columns?

I'm facing an issue with VueJS. I have a large dataset that I want to display in columns in a specific order. How can I properly insert the code for this? Thank you for any assistance. [ { "sort": 0, "title": "My title", "description": ...

Internet Explorer does not recognize the specific CSS code

My goal is to create a website that behaves differently on Internet Explorer browser. I am attempting to achieve this by using a separate CSS for IE and another CSS for different browsers. However, the IE-specific CSS does not seem to be working. <h ...

I am having trouble getting ng-change to work. Can someone explain how to properly implement ng

I am facing an issue where the ng-change function is not working for obtaining the team_id and team name. Can someone suggest a more efficient solution to resolve this problem? <th style="width:20%"> <select style="height: 40px; fon ...

Unable to choose fields and options within the popup box

Interacting with jQuery: $("#type_name").click(function(){ $("body").append('<div class="modalOverlay">'); $("#add_form").fadeIn(1000); $("#first_name").val(""); $("#email").val(""); ...

What is the process of converting an Array that is nested within an Object?

I am facing compile errors while attempting to convert an Object containing an Array of Objects. Here is the initial structure: export interface CourseRaw { metaInfo: MetaInfoRaw; gameCode: number; gameText: string; images?: ImageRaw[]; // Having ...

Working with MySQL in Node.js using async/await

Struggling with utilizing async/await in Node.js with MySQL as it consistently returns an undefined value. Can someone shed light on what could be causing this issue? See my code snippet below. const mysql = require('promise-mysql'); var co ...

A guide on accessing a dynamic object key in array.map()

How can I dynamically return an object key in array.map()? Currently, I am retrieving the maximum value from an array using a specific object key with the following code: Math.max.apply(Math, class.map(function (o) { return o.Students; })); In this code ...

Enable data insertion on a Meteor server without requiring login authentication

I am looking to develop an API that enables other apps to add new data. However, I have encountered an issue while attempting to do so. The error message "User id is required" appears because there is no logged-in user present when inserting new data. Is i ...

Adapting Vue.js directive based on viewport size - a guide

Having an element with the v-rellax directive, I'm utilizing it for prallax scrolling in this particular div: <div id="image" v-rellax="{ speed: -5 }"></div> Currently, there's a need to adjust the speed property ...

Node.js Discord error: The function channel.send is throwing a TypeError

Currently in the process of developing a Discord bot and encountering issues where it claims that the function "channel.send" is not recognized. This pertains to a command designed to enable the bot to send a message to every channel within the server. c ...

Using both Ajax and a standard submit can be applied to a single form in jQuery

I need to implement a confirm step on one of my pages. Here's what I want to achieve: When the user clicks 'submit', an AJAX request is triggered, which performs the necessary action and then displays a confirmation dialog If the user ...

Enhancing visual appearance with customized look control through the use of setAttribute

I have developed a unique custom look-controls feature and I am trying to integrate it into the scene using 'setAttribute(componentName, data)', but I'm unsure about what parameters to include. Any suggestions? Here is my approach: const s ...

Click event doesn't trigger the 'else if' statement in jQuery

Having trouble with a button click issue. In the following code, when the button is clicked, it checks if the text on the button is "day". If so, it changes the background-color of the body to red and updates the button text to "night". I am struggling wit ...

Clearing Up CSS Height Definitions

Based on my observations from other posts, it seems that to establish the height of an element in percentages or pixels, etc., the parent element's height also needs to be explicitly defined. This implies that the height settings must be specified all ...

Every time I try to use ParcelV2 to connect my frontend with my backend, I encounter the error "Uncaught referenceError: require is not defined."

Currently, I am utilizing parcel V2.7.1 in order to allow my frontend script to interact with my backend express app. I have imported axios, an npm package, but whenever I build and run parcel, I encounter an error message in the browser console stating Un ...

Exploring the capabilities of ECMAScript generators within the Intel XDK Simulator

I am attempting to utilize a generator that has been declared using function* in Intel XDK. The simulate function within XDK is said to be based on Chromium, though it's difficult to determine the specific version ('about' box and similar fe ...

JQuery email validation failing to function

I am new to JQuery and have created a basic validation script to verify email addresses. However, it does not seem to be working properly. Can anyone provide guidance on how to correct this issue? <script> $( "#email" ).blur(function() { var ...

What is the best way to align content at the center on mobile using Bootstrap 5?

I'm struggling to center elements on mobile devices, even though they look fine on desktop. Desktop: https://i.sstatic.net/I6Rtf.png Mobile: https://i.sstatic.net/4a1zS.png Desired mobile: https://i.sstatic.net/uMrEa.png I am using Bootstrap 5.3 ...

Navigating with Angular Material and md-nav-bar for efficient routing

Currently, I am delving into Angular and have opted to utilize the Angular Material library for my initial application. After tweaking some basic code borrowed from this source, which I adjusted to suit my requirements, I encountered difficulties with rout ...

Updating numerous records with varying values

Utilizing jQuery UI's sortable feature (source) allows me to rearrange elements effortlessly. By implementing custom callbacks, I can generate a list of these elements, assigning each a new position ID as I move them around. The resulting list may app ...