Iterating over an array while postponing a function

My goal is to create a continuous loop through an array of number values. These values will be used as delay parameters in a setInterval function, triggering another function each time. Here's what I've come up with:

HTML:

<p>On</p>

JavaScript:

$(document).ready(function(){
    var timings = [5000, 10000, 17000, 8000, 14000, 9000, 12000, 8000, 20000, 7000, 13000, 7000, 17000, 8000, 13000, 12000, 18000]
    //function to modify
    function modify(){
            var p = $("p").html();
            if(p === "On"){
                $("p").html("Off"); 
            } else {
                $("p").html("On");
            }
        }


    function myNewFunction(){
        for (var i = 0; i < timings.length; i++){
            var switchTime = timings[i];

            setInterval(function(){
                modify(); 

            },switchTime);

        }
    } myNewFunction();

});

I aim to have the modify function execute continuously at varying intervals. However, when I run this code, the timing doesn't seem to be functioning correctly. Any insights or suggestions would be greatly welcomed. Thank you!

Answer №1

When it comes down to it, relying on a loop won't cut it, as a multitude of setInterval (or setTimeout()) functions are initiated almost simultaneously in mere microseconds.
Each one carries out its task according to its designated timing[i], but all within a very close timeframe!

On the contrary, the key is to trigger each step only after the preceding one concludes.

Take a look at this functional example (also viewable on this fiddle), complete with visual progress tracking:

HTML:

<p id="on-off">On</p>
<p id="delay"></p>

Javascript:

$(document).ready(function(){
  var timing = [
    5000, 10000, 17000, 8000, 14000, 9000, 12000, 8000, 20000, 7000, 13000,
    7000, 17000, 8000, 13000, 12000, 18000
  ];
  function myFunction(i){
    i |= 0;
    if (i < timing.length - 1) {
      var switchTime = timing[i]
          $onOff = $('#onOff');
      $('#delay').html('i=' + i + ', delay=' + switchTime);
      $onOff.html($onOff.html() == 'On' ? 'Off' : 'On');
      setTimeout(
        function() {
          myFunction(i + 1);
        }, switchTime
      )
    } else {
      $('#delay').html('end');
    }
  }
  myFunction();
});

Answer №2

To increase the value of the variable i within the setInterval callback function.

function updateCounter(){
    for (var i = 0; i < counts.length; ){
        var timeInterval = counts[i];

        setInterval(function(){
            increment(); 
           i++;
        },timeInterval);

    }
}

Answer №3

When working in a loop, it's best to utilize setTimeout rather than setInterval. This is because setInterval sets up a timer that repeatedly triggers at the set interval (e.g. every 5 seconds, 10 seconds, and so on). On the other hand, using setTimeout within your loop ensures that the timer fires only once per iteration after the specified delay. This allows for a new timer to be set for the subsequent delay value in the next iteration.

Answer №4

If you are experiencing issues with intervals not clearing properly, it may be due to not properly using the clearInterval function. To ensure intervals are cleared before setting new ones, make sure to store the interval ID globally and clear it before setting a new interval. This will help prevent any overlapping intervals and ensure that your code runs as intended.

  1. Set an interval and save the ID globally
  2. When the callback is triggered, use clearInterval to clear the current interval
  3. Repeat this process for each new interval

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

How to extract a column as an array from an Excel file using Python

For a project I'm working on, I need to create a league table and sort it by points. To achieve this, I'm trying to extract the points column from an Excel file and order it. Here's the code I've come up with so far: output = [] x = op ...

Synchronous AJAX requests do not function properly in IE and Firefox, but they do work in Chrome and Safari

Attempting to measure download speed using an AJAX call. Below is the code snippet: var start = new Date(); $.ajax ({ url: 'https://www.example.com/perftest/dummyFile1024', cache: false, success : function() { var total = ( ...

While conducting tests on a Vue single file component, Jest came across an unforeseen token

I need help with setting up unit tests for my Vue application that uses single file components. I've been trying to use Jest as mentioned in this guide, but encountered an error "Jest encountered an unexpected token" along with the details below: /so ...

Guide: Generating a dynamic textbox on click event without needing to reload the page

I need assistance with the following form:- <form action=""> <table border="0"> <td colspan="2" class="instruction">Please select an option to search.</td> </table> <table> <tr> ...

eliminating various arrays within a two-dimensional array

I need help with a web application that is designed to handle large 2D arrays. Sometimes the arrays look like this: var multiArray = [["","","",""],[1,2,3],["hello","dog","cat"],["","","",""]]; I am looking to create a function that will remove any array ...

Typescript: Why Lines Are Not Rendering on Canvas When Using a For-Loop

What started out as a fun project to create a graphing utility quickly turned into a serious endeavor... My goal was simple - to create a line graph. Despite my efforts, attempting to use a for-loop in my TypeScript project resulted in no output. In the ...

Utilize Angular2's input type number without the option for decimal values

Is there a way to prevent decimals from being entered in number inputs for Angular 2? Instead of using patterns or constraints that only invalidate the field but still allow typing, what is the proper approach? Would manually checking keystrokes with the ...

Exploring the Power of Jasmine Testing with Ternary Conditions

Imagine a scenario where we are working with the following snippet of JavaScript code. object = _.isUndefined(object) ? '' : aDifferentObject.property; Is it possible to write a Jasmine test that covers both scenarios? Do we need to use two se ...

JSON syntax error: "r" is not a valid token at the beginning position

Currently, I am in the process of developing a web server that is based on STM32 MCU. The workflow involves the browser sending a request to the MCU, which responds with a web HTML file. Users can then adjust parameters and use a form to submit them back t ...

Restrict the number of dynamic form elements to a maximum of 10 entries

I am working on a feature where users can refer their friends and the data will be saved in a database. <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <script type='text/javascript' sr ...

Is there a way to use JavaScript to switch the entire div on and off

I have a function called done that I want to use to toggle the visibility of my "temp" division. tasks.innerHTML += `<div id="temp"> <span id="taskname"> ${input.value} </span> <button class="d ...

Unable to associate Slider values with TextFields in MaterialUI

Currently, I am trying to create a slide with 2 markers to indicate a price range and interact with it on the slide. Although I have linked the input with the slider, the connection from the slider to the input is not functioning properly. My attempt was t ...

What is the reason for and <br> not functioning in a string?

I am encountering an issue when attempting to print the content of an object. Some of the properties within the object contain tags, making it challenging to create new elements in JavaScript without knowing which properties will include these tags. How ...

Troubleshooting issues with AJAX script and JSON formatted data

Here is my complete script: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/E ...

Using Passport.js with a custom callback function that accepts parameters

I currently have this block of code: app.post('/login', passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }), function(req, res) { return res.redirect('/profile/&a ...

What impact does changing the Device Language have on a heading?

At the top of an html page, I have the word "Color" in a heading. If a user's device is set to British English, I would like the text to automatically switch to "Colour". What is the best way to accomplish this with minimal Javascript? ...

When applying the OWASP ESAPI encodeForHTMLAttribute method, I noticed that symbols are being rendered as their corresponding HTML entity numbers instead of the actual symbols

I recently started exploring OWASP ESAPI for preventing XSS and integrating the JavaScript version into my application. As per Rule #2 in the XSS prevention cheat sheet, it is recommended to "Attribute Escape" before inserting untrusted data into attribut ...

appending a set of parameters to a website address

I am currently developing an app in a Node/Express/Jade environment. Imagine that I launch my app and navigate my browser to the following URL: /superadmin/?year=2012 Upon reaching this page, I encounter a list of objects sorted in a default order. Ther ...

Methods for passing JavaScript variables to PHP

I have encountered this problem on Stack Overflow before, but I couldn't find a solution that worked for me. I am using Codeigniter and have a form where users can rate a product. What I need to achieve is to insert the user's rating into the dat ...

Is there a way to prevent a bootstrap modal from opening?

Recently, I encountered an issue with a button on my webpage: <a data-toggle="modal" href="#influencerModal" class="btn btn-primary influencer-card">Influencer Profile</a> I wanted to prevent the modal from opening when the button was clicked ...