Infinite Loop in JavaScript

Is there a way to create an infinite loop in the JavaScript code below? Currently, there is a timer set to run every 50 seconds, but I need it to continuously repeat every 50 seconds. My knowledge of JS is very limited, and while some parts of the code were explained to me, I still have a vague understanding of what's happening.

// An array that will be used later at line 30 and line 35.
var classnames = ["one","two","three","four","five","six"];

// Utilizing a CSS3 selector for classes (".classname") 
var elements = document.querySelectorAll(".ani");

setTimeout(function() {
for (var i=0; i<elements.length; i++) {
var element = elements[i];

// For example: elements[0] removes the class "one", elements[1] removes "two"
element.classList.remove(classnames[i]);

element.offsetWidth = element.offsetWidth;

// For example: elements[0] adds the class "one", elements[1] adds "two"
element.classList.add(classnames[i]);
}
}, (50*1000));

Answer №1

I'm not quite sure what your end goal is with the elements you're manipulating, but let's focus on how to make them run every 50 seconds.

While many may suggest using setinterval, I propose sticking with setTimeout and implementing a recursive approach (calling the function again from within itself using setTimeout).

The reason for this alternative recommendation is that setInterval can stack up calls to your code even if something is still processing, leading to potential issues like race conditions and performance bottlenecks. With setTimeout, we ensure that each run completes before scheduling the next one.

Below is the modified version of your code following my suggestion:

var classes = ["one","two","three","four","five","six"],
    elems = document.querySelectorAll(".ani"),
    
    cycle = function () {
        var index,
            count = elems.length,
            el;

        for (index = 0; index < count; index++) {
            el = elems[index];

            el.classList.remove(classes[index]);
            el.offsetWidth = el.offsetWidth;

            el.classList.add(classes[index]);
        }

        cycle_timer = setTimeout(cycle, 50*1000);
    },

    cycle_timer = null;

cycle();

// To stop it:
clearTimeout(cycle_timer);

Answer №2

setTimeout(function() {
  // implement your task in this block
}, 50*1000);

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

Struggling to change h2 style on WordPress?

In a WordPress page, I create three heading texts and adjust the CSS when the screen width is less than 820px. Here is the code snippet: <h1 class="block-h1">Heading 1</h1> <h2 class="block-h2">Heading 2</h2> <h3 class="block-h3 ...

Error: Loop Program Encountered Unexpected Token Syntax

Every time I attempt to run this code, a syntax error (unexpected token) appears. As someone who is still learning JavaScript, I am struggling to identify the root cause of this issue. var x = 1; var example = function(){ for(var y = 0; y < ...

Getting JSON data from an Angular JS controller can be achieved by utilizing the built-in

My user login function includes a method called logincheck, which takes in parameters and sends a request to the server. Upon success, it redirects the user to the dashboard with the member ID. this.logincheck = function(log) { var pa ...

Retrieving the first child in a tree via URL parameters using JavaScript, rather than the currently selected one

I'm currently facing a specific issue with my webpage and I will elaborate on what's happening. Within my page, I have created a list containing multiple sections. Here is an example of how it looks: <ul class="menu__list--nested active& ...

The Xero Node OAuth Authorize Callback URL is malfunctioning after granting access

When utilizing the xero-node library to produce a Request Token using the getRequestToken function, the URL provided does not automatically redirect the user to the designated callback address specified in the configuration. Instead, a screen displaying a ...

Can someone explain the purpose of adding "v=747" at the end of /site_media/base.css?v=747?

Observing a webpage's source code, I came across the following CSS declaration in the header: <link rel="stylesheet" href="/site_media/base.css?v=747" /> Could you please explain the significance of "?v=747" at the end of this CSS declaration? ...

Angular silhouette casting on CSS fold

I am attempting to recreate this design as accurately as possible, but I am struggling with replicating the shadow effect on the right side. Is it achievable using CSS? CSS: *{margin:0px;padding:0px;} html { width:100%; height:100%; te ...

For every new page, the content should always begin from the top

I recently created a React project with various components and pages. One issue I encountered is that when switching between pages using the navbar (such as home, about us, contact us), the pages resume from where I left off instead of starting at the to ...

AlignmentPositioning Customize Check Boxes with Progress Bars in Bootstrap 4

I have the code snippet below: <div class="row"> <div class="col-md-2"> <div class="custom-control custom-checkbox my-auto" style="display: inline; align-items: center;"> <input class="custom-control ...

Generating documents in Word or PDF format using PHP and Angular data

My goal is to generate a Word document using PHP for which I found a solution involving the use of headers. header("Content-type: application/vnd.ms-word"); header("Content-Disposition: attachment;Filename=output.doc"); Initially, this method worked well ...

Respond to the initial message within the "if" statement

client.on('message', message => { if (message.channel.type === 'text' && message.channel.name.toLowerCase() == "channel-2" && message.content === "test") { message.react("✅") } ...

The virtual positioning of list items in React Virtualized

Using React Virtualized in a setup similar to the snippet provided below has raised an issue. A few items are being rendered using a CellMeasurer. The last item, which indicates that more items will be loaded, is not rendering correctly. It has the wrong p ...

Utilizing Multiple Carousels on a Single Bootstrap 5 Page

I am facing a challenge in making multiple Bootstrap carousels work correctly on a single page. According to Bootstrap guidelines, each carousel should have a unique ID. However, I am struggling to implement this and only one carousel functions properly ...

How to resolve the issue of not being able to access functions from inside the timer target function in TypeScript's

I've been attempting to invoke a function from within a timed function called by setInterval(). Here's the snippet of my code: export class SmileyDirective { FillGraphValues() { console.log("The FillGraphValues function works as expect ...

What is the process for converting a Map into a Set and vice versa?

forEach() method uses the value variable twice for compatibility between Map and Set. Source This use of the same value twice is to align with Map's callback structure. It may seem odd, but it makes replacing Map with Set easier in some cases, and ...

Add multiple checkboxes in a dropdown menu to save in a MySQL database

I have a register.php and I'm trying to insert the data into users table. The problem I have is with "languages" field - I've created a dropdown list with multiple checkboxs. I want the user of course to be able to insert to his profile more tha ...

Engage with your audience using Javascript and JQuery

Currently, I have a web service that retrieves data and displays it on my client. I have implemented a button that triggers an AJAX get request to fetch new data from the service. Additionally, my web service includes functionality for adding, editing, and ...

Difficulties in Adjusting the Size of Three Image Columns within a Website's Body

While working on my website layout, I encountered a problem with inserting three image columns in the body section. The images turned out to be too large and extended beyond the footer. Moreover, the third image was larger than expected, dominating the web ...

What is the best way to combine an array of objects into a single object in typescript?

Looking for some help with converting an array of objects into a single object using TypeScript. Here's the structure of the array: myArray = [ {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'}, {itemThreeKey: ' ...

Ensure the button remains in focus after clicking on the input field: Material-Ui

I'm currently working with a material-ui dialog and I've encountered an issue. When I click on the input field, the social button loses focus which is not what I want. Here's how it looks: https://i.sstatic.net/vNRrP.png Here's the de ...