Activate sound using the setInterval function and repeating code

Check out my code snippet below:

var song = ['note1.mp3', 'note2.mp3', 'note3.mp3', 'note4.mp3']

for(i = 0; i < song.length; i++) {
  setInterval(function() {

    //play song[i]
    //or console.log(song[i]);

  }, 1000);

}

I'm running into issues with this implementation. Can anyone provide insight as to why it's not working? My goal is to play note1.mp3, followed by note2, note3, and finally note4.

Any help would be greatly appreciated. Thank you!

Answer №1

Your issue here is with the scope. There is a single variable i for all callbacks, so you need to create a separate scope for each i. Also, make sure to differentiate between the callbacks.

View solution on jsFiddle

var song = ['a', 'b', 'c', 'd', 'e'];

$.each(song, function (i) {
    setTimeout(function () {
        $("div").text(song[i]);
    }, i * 1000);
});

Answer №2

Your observation indicates that you consistently receive the final song as output. This is due to the fact that the interval function captures the loop counter i, using its value at the moment of the function call, which inevitably results in the last value being used.

It is generally advisable not to define callbacks within a loop in this manner. One alternative approach could be:

var song = ['note1.mp3', 'note2.mp3', 'note3.mp3', 'note4.mp3']
var makeCallback = function(index) { 
    return function() {
        console.log(index);
    }
}

for(i = 0; i < song.length; i++) {
  setInterval(makeCallback(i), 1000);            
}

This method creates a distinct closure for each iteration, addressing the issue.

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

Unable to access property 'map' of undefined - having trouble mapping data retrieved from Axios request

When working with React, I have encountered an issue while trying to fetch data from an API I created. The console correctly displays the response, which is a list of user names. However, the mapping process is not functioning as expected. Any insights or ...

Creating a glowing shimmer using vanilla JavaScript

After successfully creating the Shimmer Loading Effect in my code, I encountered a hurdle when trying to implement it. The effect is visible during the initial render, but I struggle with utilizing it effectively. The text content from my HTML file does no ...

Steps for displaying a division on clicking a hyperlink

I am currently working on my main menu layout in HTML, and here is the code snippet: <div id="main-container"> <div id="main-wrapper"> <div id="logo"> <h1 id="title">port ...

Tips on retrieving all visible objects in the camera view using Three.js

Is there a way to implement lazy loading of textures for meshes, loading only the ones that are within camera view without relying on an excessive number of vectors in Raycaster? ...

Exploring C programming by dissecting and analyzing targeted lines of code

As someone who is just starting out with C programming, I am currently facing a challenge of reading a file and extracting only the numerical information from it to be used in a later function. The file I am working with has a specific format: && h ...

Use ag-Grid to customize your column headers with checkboxes, allowing you to easily select or deselect all items in that column. This feature is not limited to

In my experience with ag-grid, I often find myself needing to customize the first column header to include a checkbox. This allows me to easily perform actions such as selecting all or deselecting all rows in the grid. It's important to note that this ...

How come my function is executing right away despite the setTimeout() being called?

I am working on a program that is designed to showcase how a bubble sort works. However, I would like the program to pause for one second after each swap in order to clearly demonstrate the sorting process. Below is the code I have written: function bubble ...

What is the best way to create all possible combinations of key-value pairs from a JSON array?

In my scenario, there is a JSON array with key-value pairs where the values are arrays. Here's an example: json = {foo:[1,2],bar:[3,4],pi:[5]} I am looking for a way to generate all possible combinations of these parameters for any number of keys. Th ...

Issue arises when trying to implement sidebar navigation in Angular with Materialize CSS

Just starting my Angular journey and running into some trouble trying to set up a practical and responsive menu using SidebarNav and Dropdown. I used CLI to install and configure angular2-materialize and materialize-css. To create the menu, I made a comp ...

Locate a button element and dynamically assign an identifier using jQuery or JavaScript

I am currently working on a webpage that contains two forms, both enclosed within a <DL> element. <dl> <form action="" method="POST" style="display:inline-block;"> <dl><dt></dt><dd><input class="submit" typ ...

A guide on extracting and converting strings in React to display as HTML

I am in the process of developing a simple blog app using a MERN stack. Currently, I have the functionality to create posts with just plain text. Is there a way to incorporate HTML rendering within the content of these posts? For example, a post might con ...

Is it really necessary to import React from 'react' in the index.js file when importing react is no longer required?

Currently diving into the world of React.js. I recently found out that after version 17, importing React is no longer necessary. My current React version is v18.2.0. Here's the code snippet in question: // import React from 'react'; import ...

Conditional radio button disabling in Material-ui

Currently, I am developing a React application using material-ui. My goal is to disable all radio buttons within a RadioGroup when a specific event occurs, and then re-enable them once the event is no longer active. For example, when a button is clicked, ...

The array position with the index of "0" will be accessed after using JSON.parse

I need help parsing this type of data: { "roads": [{ "road": "*IndustrialArea1", "house_number_required": true }, { "road": "Turnoff Kienbaum", "house_number_required": true }, { "road": "Maple Avenue (Eggersdorf)", "house_numb ...

CKEditor - extracting modified content with its associated HTML markup

I am currently developing my own custom Drupal plugin and I recently reviewed the code provided in the API for change events: editor.on('change', function (evt) { console.log(this.getData()); }); Using this code snippet, I am able to vi ...

After initializing the controller and postLink, ensure to reset the scope variable in the directive

I have created a basic directive: angular.module('app').directive('field', function () { return { restrict: 'E', template: '<div ng-click="clickElement()"><input id="{{inputId}}"></div& ...

Issue with AngularJS $http not responding to ng-click after first call

My landing controller uses a service that initiates the $http call by default when the App loads. However, I need to pass parameters based on click events, so I implemented an ajax call on ng-click. The issue is that I keep receiving the same data on ng-c ...

Interactive Thumbnail Selection for HTML5 Video

Having trouble with creating thumbnails? I managed to solve the cross-domain issue using an html2canvas PHP proxy. No error messages in the Console, but the thumbnails are unfortunately not showing up - they appear transparent or white. Here is a snippet ...

What is the best way to incorporate the final paragraph into the foundational code?

I'm attempting to create my own version of the lyrics for 99 Bottles of Beer Here is how I've modified the last line: 1 bottle of beer on the wall, 1 bottle of beer. Take it down and pass it around, no more bottle of beer on the wall. How ...

How to disable sorting on the top LI element using jQuery?

I currently have two separate UL elements that are being sorted using the jQuery Sortable plugin. Each UL contains between one and ten LI elements arranged in a list format. $(".sortable").sortable({ connectWith: ".sortable", cancel: '.no-dra ...