An exclusive execution of the JavaScript function is ensured

I have a JavaScript function that I want to execute 12 times in a row. Here's my approach:

Below, you'll find a list of 12 images:

<img id="img1" src=""> </img>
<img id="img2" src=""> </img>
<img id="img3" src=""> </img>
<img id="img4" src=""> </img>
<img id="img5" src=""> </img>
<img id="img6" src=""> </img>
<img id="img7" src=""> </img>
<img id="img8" src=""> </img>
<img id="img9" src=""> </img>
<img id="img10" src=""> </img>
<img id="img11" src=""> </img>
<img id="img12" src=""> </img>

Here's the definition of the respective function:

function updateImageSource(id, dynamicValue) {
      var imageUrl = "http://..."+ dynamicValue + "test";
      $("#img" + id).attr("src", imageUrl);
    }

And here's how I'm attempting to call it on each image:

var imgId = 1;
while(imgId < 13){
        updateImageSource(imgId, "dynamicValue" );
        imgId++
}

However, I'm facing an issue where the function only executes once. Can someone please shed some light on the possible cause for this behavior?

Answer №1

A for loop can be used in this situation, enabling you to achieve the desired outcome:

for (var itemID = 1; itemID <= 12; itemID++){
    insertImageSource(itemID, "my_variable");
}

Answer №2

Consider using a "for" loop instead of an "if" statement in this code:

  for (var number = 1 ; number < 13; number++) {
         addImage(number, "another_variable" );
  }

Furthermore, there is an error on the following line:

addImage(item, "another_variable" );

The correct parameter should be:

addImage(number, "another_variable" );

Answer №3

A solution to your problem is to incorporate a loop structure instead of a conditional statement in your code. By using a loop, you can repeat the function call multiple times.

Here's an alternative approach:

In order to achieve the desired outcome, you can utilize a for loop like this:

for (var itm_id = 1; itm_id < 13; itm_id++) {
  addImageSource(itm_id, "another_variable");
}

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

Replicate the form to a new one while concealing the elements and then submit it

Initially, I was working with just one form. Now, I find myself in a situation where I need to utilize a different form which contains the same inputs. This is necessary because depending on the action taken upon submission, different processes will be tri ...

Guide to incorporating the content of a div into an image source using PHP

In extracting a value from an HTML table, I encountered this syntax: $('table#showalluporders tbody tr').click(function() { var tableData = $(this).closest("tr").children("td").map(function() { return $(this).text(); }).get(); $(' ...

Sending each step for evaluation

I am currently utilizing jQuery steps within a form wizard. I would like each step to display a different form every time it changes, along with previous and next buttons. Additionally, I am looking to submit the form via AJAX. However, when attempting to ...

I noticed that my CSS style sheet is only working on three of my pages. What should I do to make sure it affects the fourth page as well?

I am currently facing an issue with my website where I have linked one .css stylesheet to 3 different pages. This is just a temporary template until I finalize the individual look of each page. After performing some div positioning on the site, most pages ...

How to retrieve the value from an editable td within a table using Jquery

I am working with a dynamic table that looks like this: <table> <tbody> <tr> <td>1</td> <td contenteditable='true'>Value1</td> </tr> <tr> ...

Tap here to switch between 2 jquery functions

Due to the deprecation of the toggle() method in jQuery version 1.8 and its removal in version 1.9, an alternative approach is needed for versions 1.11 and above. You can check out the documentation for more information. If you are looking to replicate th ...

Livereload in Gulp fails to automatically restart the server

How can I make my gulp+livereload server automatically restart and update the page when JS files are changed? Below is a snippet from my gulpfile.js: var gulp = require('gulp'), livereload = require('gulp-livereload'), ...

The menu will expand to full width, with each list item evenly sharing the width to achieve full coverage

I am currently facing an issue with my horizontal menu on my website. I want the menu to stretch across the full width of the site, but I can't seem to get it right. Here is the code for my menu: <nav> <ul id="menu" class="menu"> &l ...

Unique mechanism for tracking clicks in ASP and C#

Is there a preferred method for showing a click counter on an HTML page when working with a .aspx file that connects to a .cs file pulling data from a SQL server, without relying on an external text file for tracking purposes? I'm trying to avoid usin ...

Issue encountered when trying to import an image URL as a background in CSS using Webpack

I have been trying to add a background image to my section in my SCSS file. The linear gradient is meant to darken the image, and I'm confident that the URL is correct. background-image: url(../../assets/img/hero-bg.jpg), linear-gradient(r ...

Accelerate Image Preloading速

I am currently in the process of creating a website that features divs with background images. Although I am new to JavaScript, I am eager to learn more about it. My main goal is to preload these images so that visitors do not encounter any delays or bla ...

Issues with Await and Async functionality in Angular and Ionic 4 causing unexpected behavior

Struggling to show error messages during the sign-up process? Constantly encountering the same issue in your code? The error TS1308 is throwing you off: 'await' expression is only allowed within an async function. Take a look at this problemati ...

What steps can I take to eliminate the initial delay when it is first invoked?

My function is being called every 10 minutes like this: var interval = self.setInterval(my_func, 600000); function my_func(){ $.ajax({ url: 'xxxxxxxx', success: function(response) { var data= JSON.parse(response); dis ...

Mastering CSS: Optimizing Div Placement Across Sections

I am currently working on developing a sleek and modern landing page with multiple sections, each designed to catch the eye. This style is all the rage at the moment, featuring large headers, ample padding, bold text, and a visually appealing divider betwe ...

Redis: Unable to establish a connection as net.connect is not recognized as a

I'm struggling to integrate Redis with nodejs Encountering issues during execution Despite using the same code, I am facing this error: Here's my code snippet: import { createClient } from 'redis' export const client = createClient({ ...

Unity3D: Troubleshooting a Code Issue

Encountering an issue with my code and struggling to find a solution. I've tried moving my c# script up to the standard assets folder as suggested in my research but it didn't resolve the problem. Any assistance would be greatly appreciated! Than ...

Can you explain the meaning of "|| [];"?

Can you explain the significance of || [] in this code snippet and provide some insight into why it's included? getPair: function() { return this.props.pair || []; }, ...

Struggling with UI-Grid's single filter feature when dealing with intricate data structures?

I'm currently working with UI-Grid and facing a challenge while applying a filter to some complex data using their single filter example. Initially, everything runs smoothly when I use simple selectors. However, as soon as I attempt to delve one level ...

The Npm generate script is failing to create the necessary routes

I've integrated vue-router into my nuxt project, but I encountered an issue when running npm run generate - it generates everything except for my pages. I suspect the problem lies with the router implementation as I didn't face any issues before ...

What is the best way to hide the select arrow in an input-group using Bootstrap 4?

Is there a way to get rid of the unsightly double arrow in the select element? I have tried various solutions I found online, but none seem to be effective. <div class="form-group"> <label for="date">Date</label> <d ...