Troubleshooting Issues with Array Loops in JavaScript

I'm encountering an issue with my code that is supposed to open different links in an iframe one after the other, with a 3-second delay between each. However, it seems to be skipping directly to the last link in the array instead of following the intended sequence.

Are there any JavaScript experts who can help me troubleshoot this?

 <html>
 <head></head>
 <body>

 <a href="http://www.google.com">Google</a><br />
 <a href="http://www.thinkgeek.com">ThinkGeek</a><br />
 <a href="http://www.themetapicture.com">The Meta Picture</a>

 <iframe src="http://www.google.com" id="myid" name="main" width="1024" height="768">
 </iframe>

 <script>
 function getLinksArray() {
     for (var i = 0; i < document.links.length; i++) {
         var linx = document.links[i].href;

         // create a closure for each loop iteration
         (function(linx) {
           setTimeout(function() {
             openLinks(linx);
           }, 3000);
         }(linx));

     }
 }

 function openLinks(link) {
 document.getElementById("myid").src = link;
 }

 window.onload = getLinksArray();
 </script>
 </body>
 </html>

Answer №1

For optimal results, consider using 3000 * i as the delay time. This will ensure each execution occurs after 3000ms (3 seconds) and since they are executed sequentially, the final one will be the most noticeable.

// ...
setTimeout(function(){
  // ...
}, 3000 * i);
// ...

Answer №2

I believe this code snippet may be the solution you are looking for, as it avoids causing excessive delays. I haven't conducted performance tests on both options, so I cannot definitively say which one is superior. However, I did want to ensure that you were aware of this alternative approach.

let anchors = document.links;
(function loadLink(index) {          
    setTimeout(function () {   
        document.getElementById("myid").src = anchors[index].href;
        if(anchors[++index])
        {
            loadLink(index);
        }
    }, 3000)
})(0);

Answer №3

If you're looking to add a timed iteration into your code, consider this approach:

function loadLinkWithDelay(i) {
    document.getElementById("myid").src = document.links[i].href;
    if (i < document.links.length) {
        window.setTimeout(function() { loadLinkWithDelay(i+1) }, 3000);
    }
}

window.onload = loadLinkWithDelay(0);

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

Refresh the data using the Ajax function

I am attempting to implement a delete function using Ajax. function delCatItem(catitem){ var theitem = catitem; $.ajax({ url: "movie/deleteitem/", type: "POST", data: { "movieid" : catitem ...

Unable to confirm the validity of the object within another object

To retrieve the values of the object, I use the following code snippet: const link = $("#link").val(); const state = $("#state").val(); etc... The Object is then constructed with these values: const departmentObject = { position, name, link, sta ...

How can one utilize the this.$q Quasar object within the setup() function in Vue 3 Composition API?

Here is a component script written in Options Api: <script> export default { data() { return { model: null, }; }, computed: { isMobile() { return this.$q.screen.xs || this.$q.screen.sm; } } }; </script> If y ...

What is the equivalent of Android Input/Output stream in TypeScript/JavaScript?

My current task involves sending data from Angular to an Android device. The requirement is for the data to be sent to the Android device using its input/output stream methods. If you are unsure of what I am asking, please provide assistance and let me kn ...

What is the best way to extract all values from an array that meet a specific condition?

I have an array structured like the following and I'm looking to retrieve all values where the description matches a given value. I understand how to retrieve the first array value where the condition is met, but I'm unsure of how to retrieve all ...

Using AngularJS: The ultimate guide to invoking a service within a module

I have a controller that successfully calls a service. However, I now need to access a method within that service from another module. How can I achieve this? BaSiderbarService: (function() { 'use strict'; angular.module('BlurAdmi ...

Is it possible to have the browser handle the MIME type for downloading Wicket ByteArrayResource exclusively?

My current situation involves fetching documents with attachments from a CouchDB using the Ektorp library in Java code. These documents are successfully mapped into Java objects. To make these attachments accessible in the browser, I am creating a ByteArra ...

Customizing Paths in Express Handlebars

I have a query regarding setting up custom folders in Express.js Here's my situation: I need to implement logic where if a specific name is present in my database, the paths for CSS and JS files should be altered before rendering. By default, my pat ...

Can the length of an Array object be modified?

Is there a way to transform self in an Array into an entirely new array? What code should I use in the commented section below? class Array def change_self #transforms this array into `[5,5,5]` end While I understand why it's not possible to ...

When a node using express encounters :id, it is directed to a specific location

Currently, I am in the process of creating a small API collection to familiarize myself with nodejs using express. In my project, I have included the line app.use("/v1/phrases", phraseRouter); Within the router file, the code looks like this: co ...

Assassin eradicated from list of cast members

In my quest to select a killer from the Cast Members Array for the game, I want the function to pick one person as the killer and then remove them from the castMember player array. Once the killer is chosen, they should be removed from the survivors array ...

Converting data from an array to JSON format using PHP

For my AJAX request to work, the data needs to be formatted as shown in the code snippet below. { "columns": [ [ "Name" ], [ "Position" ], [ "Office" ], [ "Extn." ], [ "Start date" ], [ "Salary" ] ], ...

Encountering the error code 'ERR_EMPTY_RESPONSE' while utilizing an AJAX-powered live search feature

My website features a live AJAX search bar that retrieves records from a MySQL database. However, when users repeatedly conduct searches by modifying the search criteria, some web browsers display an error message stating 'ERR_EMPTY_RESPONSE'. ...

Create a personalized Vector class that functions similarly to an array in C++

How to create a custom vector class and overload all operators: template <class T> class Vector{ private: T * arrayOfObjects; // other class members public: Vector(){ arrayOfObjects = new T[100]; } Vect ...

Update the dropdown menu using jQuery when resizing

I am seeking a solution to adjust the behavior of my dropdown menu based on the screen resolution, utilizing jQuery. Currently, I have set it up so that above 1024px, the ul.level-2 menu is triggered by hovering over the button, and below 1024px, it respo ...

Outputs an excessive amount of [object Object] within a list instead of the expected values

My jquery code is causing some unexpected behavior. After entering text, the display only shows [object Object], however when I use console.log(areaname) the result is correct. I have tried stringifying the data but the issue persists $('#arealist& ...

Issue detected in rxjs-compat operator's shareReplay file at line 2, column 10:

I've encountered an issue with the angular material spinner I'm using in my project. The error message is as follows: ERROR in node_modules/rxjs-compat/operator/shareReplay.d.ts(2,10): error TS2305: Module '"D:/ControlCenter/ofservices ...

Contrasting $route.current.pathParams with $routeParams

I'm currently attempting to update a URL without having to refresh my page, and I came across this solution that I am working with: https://github.com/angular/angular.js/issues/1699#issuecomment-45048054 Upon further testing, I found that the followi ...

What is the best way to list the choices associated with a specific category?

The Node.js package I'm currently working with requires an argument of a specific type, which I can see is defined through a TypeScript declaration as follows: export declare type ArgType = 'A' | 'B' | 'C'; I am interes ...

Choose just a single checkbox within the gridview and modify the selected row

I have a GridView with a column containing an ASP CheckBox control. I want the user to be able to check one checkbox and then click on the edit button to edit that particular row. Below is my code for this functionality: <asp:GridView runat="server" C ...