"Exploring the Art of Showcasing Duplicate Image Count from User Input in an

I need to showcase multiple duplicates of 2 different images on a webpage. Users are asked for the duplication speed, which I have already implemented, and also how many copies of each image they want.

function show_image() {
  var img = document.createElement("img");
  var img2 = document.createElement("img");
  img.src = "map.png";
  img2.src = "figure-front.png";
  document.body.appendChild(img);
  document.body.appendChild(img2);
  setTimeout("show_image()", speed);
  max = 0;
  max++
  if (max = count) {
    return;
  }
}
<!DOCTYPE HTML>

<html lang="en">

<head>
  <meta charset="UTF-8>
  <title>JavaScript Slide Show</title>
  <script src="ShowImages3.js></script>
  <script>
    var speed = prompt("Enter the speed at which you want to duplicate", "");
    var count = prompt("Enter how many copies of each image you want to display", "");
  </script>
</head>

<body onLoad="show_image()">

</body>

</html>

Nevertheless, it seems to be running indefinitely

Answer №1

To fix the issue, make sure to move the setTimeout function and use either == or === for comparison instead of = which is for assignment.

Avoid using body onload and opt for an eventListener instead as it is considered better practice.

Here is a more organized version utilizing setInterval. I have also used >= in the test condition.

I set an empty string for the speed and prompt values so that I can check if they exist using if (speed && prompt) after converting them to numbers with the unary plus operator. Note that I did not include checks for inputs other than numbers and empty strings.

let count = 0, cnt = 0, tId;

const show_image = () => {
  if (cnt >= count) {
    clearInterval(tId); // stop
    return;
  }
  const img = document.createElement("img");
  const img2 = document.createElement("img");
  img.src = "map.png";
  img2.src = "figure-front.png";
  document.body.appendChild(img);
  document.body.appendChild(img2);
  cnt++; // next
};
window.addEventListener("DOMContentLoaded", () => {
  let speed = +prompt("Type how fast you want to duplicate", "");
  count = +prompt("Type how many image of each you want to duplicate", "");

  if (speed && prompt) tId = setInterval(show_image, speed)

});

Alternatively, consider encapsulating the variables like this:

const generate = (count, speed) => {
  let cnt = 0;
  let tId;

  const addImages = () => {
    if (cnt >= count) {
      clearInterval(tId); // stop
      return;
    }
    const img = document.createElement("img");
    const img2 = document.createElement("img");
    img.src = "map.png";
    img2.src = "figure-front.png";
    document.body.appendChild(img);
    document.body.appendChild(img2);
    cnt++; // next
  };

  tId = setInterval(addImages, speed);
};

window.addEventListener("DOMContentLoaded", () => {
  let speed = +prompt("Type how fast you want to duplicate", "");
  let count = +prompt("Type how many image of each you want to duplicate", "");

  if (speed && count) {
    generate(count, speed);
  }
});

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

Preventing multiple clicks by toggling the HTML tag on and off

Here is the jQuery structure that I am currently working with: $(document).on('click', '.view-details', function () { $(this).prop("disabled", true); // API call1 // API call2 // API call3 $(this).prop("disabled" ...

Is there a way to retrieve the current object as a JSON string from inside the object using either jquery or javascript?

Looking for a way to return the current instance as a JSON text so that the values can be sent via an ajax request to a server-side script. Uncertain about where to apply the "this" keyword in a jQuery selector function Actor(){ this.input=function(pnam ...

NextJS: Retrieve the information in its initial state

Is there a way to retrieve the original format of a value? For example: The values in my textarea are: Name: Your Name Email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f980968c8b9c94989095b994989095d79a9694">[email ...

A guide on adding a personal library to Ember using npm

Despite the abundance of blog posts discussing it, I am still facing challenges in utilizing a custom library as a dependency for my ember application through npm. I have developed a WebGL library and successfully imported it into my Ember app by installi ...

Events are not being triggered when using node busboy with express 4 and ng-file-upload

I am currently utilizing the mean.io stack along with ng-file-upload module. Does anyone have any insights as to why the events are not being triggered? Your assistance would be greatly appreciated. Client controller('ArticleParentCtrl', [&apo ...

I'm attempting to install the "firebase" package using npm, but I keep encountering a python-related error message during the installation process

I am experiencing difficulties while attempting to install the firebase package in a local expo-managed project. Unfortunately, I keep receiving the following error message... Here is the error message that I am encountering I have already tried using "e ...

Customizing checkbox appearance without including a label

After following a tutorial on how to style checkboxes found here, I was able to create a custom styled checkbox. However, I noticed that when I removed the label from the checkbox, it disappeared and was no longer visible. Is there a way to display the c ...

Having trouble with your Bootstrap Accordion panels?

I am in the process of creating a unique accordion-style panel for a client's website. However, I am facing difficulties as this is my first attempt at setting up such panels and it doesn't seem to be functioning correctly. I'm not sure if I ...

Is there any more Angular code to be bound using ng-bind-html or ng-bind?

Hey there! Just a quick Angular inquiry: <div class="_minimal_size margin_10_middle"> <div class="_50 espaciado_0_20"> <p ng-bind-html="eirana_knows.feedback"></p> </div> <br class="clear"/> </div ...

Troubleshooting Automatic Scrolling Problems in React Virtualized

In my project utilizing react-virtualized v-9.21.2 to showcase a list, a problem arises when adding a new item. I employ a method of clearing the cache and updating the listKey to enable auto resizing the height. However, this results in an undesired behav ...

Utilizing .env Variables in NestJS Main App Module for Establishing Database Connection

I recently embarked on my first NestJS project, where I initially had a hardcoded database connection string in app.module.ts that worked perfectly fine. However, our project requirements called for fetching the database configuration values from environm ...

`Is there a way to avoid extra re-renders caused by parameters in NextJS?`

I am currently in the process of implementing a standard loading strategy for NextJS applications using framer-motion. function MyApp({ Component, pageProps, router }) { const [isFirstMount, setIsFirstMount] = useState(true); useEffect(() => { ...

What is the best way to include a substantial amount of HTML in a Vue.js template?

As a newcomer to Vue.js, I have a question regarding the rendering of a large amount of HTML in a Vue.js template. When I include around 500 lines of plain HTML code in my template and run npm run dev the compiling process becomes extremely slow or d ...

A guide on retrieving bytecode from a specific PDF using Angular

Can anyone help me with extracting the bytecode from a selected PDF file to save it in my database? I keep encountering an error stating that my byte is undefined. Could someone please review my code and identify what might be causing this issue? I attemp ...

Vue transition isn't functioning correctly without the specified mode parameter of 'out-in'

I'm struggling to comprehend why the transition doesn't smoothly roll from top to bottom without mode="out-in". When using out-in, it rolls as expected (albeit with a delay), but without it, the transition just suddenly appears after rolling dow ...

Steps to align table next to the paragraph tag

I am facing an issue trying to align a table inline with the p tag in my HTML code. I have attempted to make minimal changes to achieve this, but it is not working as expected. Here is the code I have tried: <p>ABCD</p> <table style = displ ...

Using Angular.js to fetch information from a MySQL database

I'm currently trying to retrieve data from a MySQL database in an Angular.js application. I have gone through multiple tutorials, but unfortunately, none of them have been successful for me. I have a PHP script that returns a JSON array with example ...

Using Selenium Webdriver to target and trigger an onclick event through a CSS selector on a flight booking

I've been running an automation test on the website . When searching for a flight, I encountered an issue where I was unable to click on a particular flight. I initially tried using Xpath but it wasn't able to locate the element when it was at th ...

AngularJS Error: Attempting to Access Undefined Object - Jasmine Testing

Encountering an error while running Jasmine tests when trying to mock/spy on an API call in the tests. Below is the code snippet responsible for calling the API: UploadedReleasesController.$inject = ['$log', '$scope', '$filter&apo ...

What strategies can be implemented to increase the number of backlinks?

<script type="text/javascript"> $(document).ready(function() { var linkas = $("#button").attr("value"); $('#button').click(function(){ $.get(linkas, function(data){ $(' ...