Ways to reduce lag while executing a for loop

How can I optimize my prime number generation process to avoid lagging? For example, is there a way to instantly display the results when generating primes up to 1000?

HTML:

<!DOCTYPE html>
<html>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <title>Prime Generator</title>
  <h1>
  Welcome to my online prime generator!
  <h1>
  <style>
    .w3-gold,.w3-hover-gold:hover{color:#fff!important;background-color:#c9a000!important}
    .w3-btn {
    background-color: #c9a000;
    color: white;
    padding: 16px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 0px;
    -webkit-transition-duration: 0.4s; 
    transition-duration: 0.4s;
    cursor: pointer;
    float: right;
    }
    }
    .button1 {
    background-color: black;
    color: white;
    }
    .button1:hover {
    background-color: #e7e7e7;
    color: black
    }
    .button2 {
    background-color: #c9a000;
    color: white;
    }
    .button2:hover {
    background-color: #e7e7e7;
    color: black
    }
  </style>
  </head>
  <body>
    <div class="w3-container">
      <div class="w3-card-4">
        <div class="container w3-gold">
          <h2>Input Form</h2>
        </div>
        <form class="w3-container">
          <p>
            <select class="w3-select" name="option" id="option">
              <option value="" disabled selected>Generate or Choose?</option>
              <option value="1" >Generate</option>
              <option value="2" >Choose</option>
            </select>
            <input class="w3-input" id="inputt" type="text">
            <label class="w3-text">Type in a number<label>
          </p>
          <p>     
          <div class="w3-btn button2" id="BT2">Clear</div>
          <div class="w3-btn button1" id="BT1">Proceed</div>
          <div id ="done"></div>
          <div id="out"></div>
          <div id="gout"></div>
        </form>
        <script>
          function prime(num) {
            var stop = num % 2 == 0
            var num1 = 2
            var num2 = 2
            while (stop == false && num2 <= Math.sqrt(num)) {
                stop = num1 * num2 == num
                num1++
                if (num1 == num) {
                        num1 = 2
                        num2++
                }
            }
            if (stop == true) {
                return(num + " is not prime.")
          } else {
            return(num + " is prime")
          }         
          }
          document.getElementById("BT1").addEventListener("click", function(){
          if (isNaN(document.getElementById("inputt").value) == false && document.getElementById("inputt").value != "" && document.getElementById("option").value == 1) {
          document.getElementById("out").innerHTML = "<br> Generating up to " + document.getElementById("inputt").value + "!"
          document.getElementById("gout").innerHTML = ""
          for (num3 = 1; num3 <= parseInt(document.getElementById("inputt").value); num3++) {
            document.getElementById("gout").innerHTML = document.getElementById("gout").innerHTML + "<br>" + prime(num3)
          }
            document.getElementById("done").innerHTML = "done!"
          } else if (isNaN(document.getElementById("inputt").value) == false && document.getElementById("inputt").value != "" && document.getElementById("option").value == 2) {
            document.getElementById("out").innerHTML = "Checking if " + document.getElementById("inputt").value + " is prime!"
            document.getElementById("gout").innerHTML = "<br>" + prime(parseInt(document.getElementById("inputt").value))
          } else if (document.getElementById("inputt").value != "") {
          document.getElementById("out").innerHTML = document.getElementById("inputt").value + " is not a number!"
          } else {
          document.getElementById("out").innerHTML = "Thats a blank space!"
          }
          });
          document.getElementById("BT2").addEventListener("click", function(){
          document.getElementById("gout").innerHTML = ""
          document.getElementById("out").innerHTML = ""
          document.getElementById("done").innerHTML = ""
          });
        </script>
      </div>
    </div>
  </body>
</html>

Answer №1

If you need a quick solution, you can update the for loop with the code below:

let result = calculateValue(input);
let content = document.createTextNode(result);
let lineBreak = document.createElement('br');
document.getElementById("output").appendChild(lineBreak);
document.getElementById("output").appendChild(content);

The delay is likely due to the fact that using innerHTML is a time-consuming process.

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

Accessing JSON array values in a nested controller in AngularJS can be achieved by using

How can I access a Json array value in another controller? I am working with nested controllers where the nested controller should return the first character of the first name and last name. For example, if my first name is Anand Jee, it should return AJ. ...

What is the best way to specify the border color of a fieldset?

Is there a way to set the border color of a fieldset while removing the default border color? I have tried using a class but it doesn't seem to work as expected. How can I achieve setting the border color for the fieldset? <fieldset class="field_s ...

Incorporating Ace Editor into a jQuery UI Resizable Element

I am attempting to create a resizable Ace editor by placing it inside a resizable component. Despite my efforts with the jQuery UI Resizable component, I am unable to get the ace editor to display within the resizable component. Code: <!doctype html> ...

Show the selected row's data from a gridview in a dropdown menu

I am facing an issue with displaying the selected row value in a dropdown list. Can anyone assist me with this problem? Here is an example scenario: Upon looking at the image, you will notice that the selected row's Department and Charge values in t ...

Shift heading 1 as well as heading 2 to the image's right side

Is it possible to position <h1> and <h2> to the right of an image while ensuring that <h2> is displayed below <h1>? Any suggestions on how I can achieve this layout? This is my current code <html> <link rel="stylesheet" h ...

Bootstrap doesn't display in the dropdown menu

Struggling to get a dropdown menu to display on my page, my HTML code is: <div class="dropdown d-inline"> <div class="widget-header mr-3"> <button href="#" class="icon icon-sm rounded-circle border" data-toggle="dropdown"><i cl ...

Step-by-step guide: Uploading files with Ajax in Codeigniter

I am facing an issue with updating data and uploading an image when editing a row in my grid. Although the data is successfully updated, I am encountering difficulties in saving the image file to a folder. Here is what I have tried: While using AJAX, I ...

Retrieving PHP variable within a JavaScript file

I have a PHP script running on my server that tracks the number of files in a specific directory. I want to retrieve this file count ($fileCount) in my JavaScript code. numberOfImages.php: <?php $dir = "/my/directory/"; $fi = new FilesystemIterator($d ...

No information retrieved from Ajax request

I've been utilizing the following jQuery code to execute an ajax call: $.ajax({ url: "/projects/project/xGetProjectStatus", type: "GET", dataType: "json"}) .done( function(request){ alert(request.responseText); ...

Applying CSS blur filter to container without affecting its content

I'm trying to create a hover effect where an image within a parent div transitions into a blurred state. However, I've run into an issue where if the image is set to 100% width/height of the parent div, there is a visible bezel of the parent&apos ...

Combining Python Bottle with Polymer Paper Elements

My website currently has a variety of forms where users input information, which is then used to calculate and display new content using Javascript. I rely on Python Bottle for user registration, form auto-filling from the backend and database management. ...

Duplicate the identical data retrieval query, this time utilizing a JavaScript Ajax post method

To enhance the data request query, implement a JavaScript Ajax post method to avoid page refresh when the button is pressed. This will allow for requesting another page and displaying it in a designated section on the webpage. Here's the code snippet ...

All the details from this run are available in the npm run dev log on Ubuntu

Good day! I've been working on deploying a page built in vue.js, and after uploading all the files successfully, I encountered an issue when trying to run "npm run dev." No matter what I try, including re-installing npm dependencies and starting from ...

"Dynamically generated websites, backend processing, React framework Nextjs, Content Management System WordPress

I'm interested in creating a primarily static site using Next.js, but I also need the ability to provide customers with price estimates based on their specifications. The calculation process needs to be kept private and not exposed to anyone else (oth ...

Whenever the state of a React component is modified, it does not automatically trigger a re

Currently, I am utilizing the React Infinite Scroller library to display a list of posts. Interestingly, my load more results function seems to be triggered three times, resulting in the update occurring thrice (verified through console.log). For renderi ...

Learn the process of utilizing JavaScript/Node.js to dynamically upload images onto a webpage directly from a database

Currently, I am developing a web application and building a user profile page where I aim to showcase user information along with a profile picture. Working with node/express/jade stack, I have a javascript file that manages loading the appropriate jade vi ...

Adjust the pagination length within the jQuery DataTables plug-in

I am looking to customize the pagination length in DataTables plug-in for jQuery. Specifically, I want to calculate the number of pages on the server side and display the correct amount of buttons on the client side. Can anyone provide guidance on how to ...

A set of four responsive divs arranged vertically

Confession time... I'm facing a challenge with this task... I'm attempting to create a responsive page with 4 stacked divs. Here are the guidelines for each div: The header div: The text should be at the bottom, serving as a slogan placed clo ...

Building a custom HTML and JavaScript player to showcase multiple videos on a webpage

UPDATE: The solution has been discovered, shared, and marked as the top answer below. In the process of creating my portfolio website using HTML, CSS, and JS, I encountered a challenge regarding the addition of multiple videos on various pages. While fol ...

Managing Multiple Operations in Angular Firestore

For the past few weeks, I've been grappling with the theory behind this issue. Despite scouring the internet for solutions, I haven't found anything truly helpful. So, I'm turning to the SO community for the first time. In my Firestore data ...