Passing a number variable from a function to setInterval using JavaScript

const exerciseItems = [ 
  ["crunches", 30], 
  ["crunches", 45], 
  ["squats", 30], 
  ["squats", 45], 
  ["lunges", 30],
  ["lunges", 45], 
  ["wall sits", 30],
  ["wall sits", 45], 
  ["push ups", 30],
  ["push ups", 45], 
  ["leg ups", 30],
  ["leg ups", 45], 
  ["jumping jacks", 30],
  ["jumping jacks", 45], 
  ["sumo squat", 30],
  ["sumo squat", 45] 
];

I need help with a JavaScript function that involves iterating through the 'exerciseItems' array, extracting the number value from each item, and using it as the delay for a setInterval outside of the function. Is this feasible?

Your assistance is greatly appreciated as I am still in the process of familiarizing myself with JavaScript.

Check out the demo here: https://jsfiddle.net/mattbtay/dcqdf8ng/1/

Answer №1

It is important to note that while setInterval() has a fixed duration between iterations, using a repeated setTimeout() call for each iteration allows for a varying delay between them. By setting the delay for the next setTimeout() based on the previous selection, you can achieve a recurring timer with a changing interval.

If we consider your jsFiddle example, where you seem to want to randomly select an item from an array each time, here is a concept of how it can be implemented. The units of time values were not specified, so I assumed they are in seconds.

function handleArray(arr, processElement, finished) {
    var data = arr.slice();
    
    function iterate() {
        if (data.length) {
            var index = Math.floor(Math.random() * data.length);
            var element = data[index];
            
            data.splice(index, 1);
            
            processElement(element[0], element[1]);
            
            setTimeout(iterate, element[1] * 1000);
        } else {
            finished();
        }
    }
    
    iterate();
}

handleArray(items, function(task, duration) {
      $('#task').html(task + ' takes ' + duration + ' seconds');
}, function() {
      // Executed when all tasks are completed
});

Answer №2

Illustrating a process of randomly selecting and removing items from a list in HTML, waiting for a specified time period, and repeating the process until all items have been removed. Upon completion, the .then function from the promise is triggered.

var items = [
  ["crunches", 30],
  ["crunches", 45],
  ["squats", 30],
  ["squats", 45],
  ["lunges", 30],
  ["lunges", 45],
  ["wall sits", 30],
  ["wall sits", 45],
  ["push ups", 30],
  ["push ups", 45],
  ["leg ups", 30],
  ["leg ups", 45],
  ["jumping jacks", 30],
  ["jumping jacks", 45],
  ["sumo squat", 30],
  ["sumo squat", 45]
];


function removeItems(processItemRemoved) {

  return new Promise(function(resolve, reject) {
    function removeItem() {

      if (items.length) { // checking if there are items left to remove

        var randomIndex = Math.floor(Math.random() * items.length); // selecting a random index within the range
        var item = items[randomIndex]

        items.splice(randomIndex, 1) // removing item from the array

        processItemRemoved(item) // processing the removed item

        setTimeout(removeItem, item[1]) // calling the function again after waiting for 'item[1]' milliseconds
      } else { // when all items are removed, triggering the resolve method
        resolve()
      }
    }
removeItem()
  })


}


removeItems(function(item) {
  $("#activity").html(item)
}).then(function(){
console.log("all items finished")
})
#activity {
  text-align: center;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-md-12">

      <div class="jumbotron">
        <h1 id="activity"></h1>
        <button class="btn btn-primary" id="startBtn">Begin</button>
      </div>

    </div>
  </div>
</div>

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

The toggleClass() function is only toggling between a single class

I'm currently facing an issue with a jQuery/Angular function that is triggered on click. <a ng-click="like()" href="#" class="like like--yes"></a> Essentially, my goal is to switch between the classes like--yes and like--no when the like ...

Learn how to successfully place a draggable object into a sortable container while ensuring that the dropped item is a personalized helper element rather than the original object

The jQuery draggable/sortable demo showcases the process of dropping a clone of the draggable item (both draggable and sortable elements share the same structure). However, I am interested in dropping a different DOM structure. For example, when dragging a ...

Is there a way to streamline this function that checks for a sequence?

public boolean CheckStairs() { Arrays.sort(collector); for (int c = 0; c < collector.length; c++) { if (collector[5] - collector[4]==1 && collector[4] - collector[3]==1 && collector[3] - collecto ...

Tips for updating multiple documents in a MongoDB database using an array of values

I have a range of Product items in my inventory and when a client places an Order, they submit an array of objects. Each object in the array includes the _id product (objectId) and the quantity they purchased. [ {producId: "dshsdsdh72382377923", quantity: ...

A guide on how to replicate an array multiple times to suit your requirements

https://i.sstatic.net/Z73UG.png In this code snippet, Array.from performs a magic trick by returning an array five times. The purpose behind this is to have certain values hard coded into the HTML: <q-table :rows="rows" :columns="co ...

Interested in halting the code execution once a match is found?

In Angular JS, I have developed a service method that checks whether any of the potential statuses in an array (pendingApplications) match any of the set statuses in another array (applicableStatuses). In order for this to function correctly, the method ...

Switch up the header's date format on NGX-Print

Within my application, I am utilizing ngx-print with Angular 8. When I click the print button, a date in the format mm/dd/yy is added to the header. However, I would like to change it to dd/mm/yy. Despite searching, I have been unable to find any document ...

Display the tooltip and highlight a specific pie slice when clicking on the legend of a pie chart in HighCharts

Hello everyone! I am looking for a way to display tooltips with legends on mouse hover and click events of a pie chart, similar to when hovering over pie slices. Additionally, I want the selected pie slice to slide out upon selection. Currently, I am usin ...

What is the best way to dynamically add a class to the right navigation element in Vue.js when the :class binding only accepts boolean values?

My issue involves implementing a fixed navigation bar with the following structure: <nav class='navigation'> <div :class="{ active: }" @click='scrollTo(".test1")'></div> <div :class=" ...

Prevent clicking with the mouse in a specific area of the screen

Is there a way to prevent mouse clicks on my website everywhere except for a specific div in the center? I'm not sure how to achieve this, any ideas? ...

What is the process of selecting a hyperlink?

Currently working on enhancing the functionality of my script. The main purpose of this script is to download a page using curl in PHP for authorization purposes. Once the page is downloaded, I need to interact with a button labeled "LOGIN" to input my log ...

React is set to re-render an array even when the key of an item has remained

Below is a simple code snippet demonstrating a list: class List extends React.Component { render() { const listComponent = this.props.numbers.map((number) => <Item key={ number.toString() } value={ number } />, ); ...

What is the process of converting a torch tensor into a collection of numpy arrays in Pytorch?

I am facing a challenge with a torch tensor that has the size torch.Size([32, 3, 64, 64]). My goal is to convert the tensor into a form that can satisfy the following assertions: assert(type(images) == list) assert(type(images[0]) == np.ndarray) assert(l ...

There seems to be an error with the return from the `mapDispatchToProps` function in `

I've been working on getting my v6 redux-form to render in the App component in order to display it in the browser. However, I keep encountering this error: Uncaught Error: `mapDispatchToProps` must return an object. Instead received function () { ...

Is there a way to determine if an integer can be expressed as a linear combination of numbers within an array?

I have been trying to determine how to verify whether an integer can be represented as a linear combination of elements within a given array that has a length of n. So far, I have successfully written code for the scenario where n=2, but I am uncertain abo ...

Navigating up and down effortlessly using bootstrap

My webpage has a collapsible form located near the bottom, but when it's opened users must scroll down to see all of it. Is there a way to automatically scroll down when it's opened and then scroll back up when closed? Take a look at my code: & ...

How can I initiate a button click event in aspx by pressing the "Enter" key on a textbox, with the button click event being defined in the source cs file?

I am trying to trigger the btnSearchSuiteGroup_Click event when the "enter" key is pressed on the txtSuiteGroupName textbox in the aspx file. Below is the code snippet: <asp:TextBox ID="txtSuiteGroupName" runat="server" clientidmode="Static" CssClass=" ...

Node.js array push operation malfunctioning

let retrievalQuery = "SELECT cp.*,ud.user_id,ud.firstname,ud.lastname,ud.displayname,ud.profile_pic,c.challenge_name from `challenge_post` as cp INNER JOIN `user_details` as ud ON cp.challenge_user_id = ud.user_id INNER JOIN `challenge` as c ON c.id = ...

Is it possible to have separate click functions for the onclick attribute and jQuery click handler on an anchor tag, instead of just calling one function through onclick?

Attempting to implement multiple click handlers for an anchor tag: one using the "Onclick" attribute handler and the other using a jQuery click handler. This excerpt is from my HTML file. <html> <head> <script src="http://code.jquery.com ...

A tutorial on dynamically adding fields with a dropdown list (populated from a database) and a text box using PHP and JQuery

I have multiple form components that I need to add dynamically, allowing users to add more than one. Firstly, there is a dropdown list with values populated from MySQL, followed by a text box for inquiries entry. The dropdown list displays a list of users, ...