Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Can someone tell me why this JSfiddle repeats the first song when finishes playing?

This is a super quick question. Here is a piece of code that plays an array of songs in order. Somehow, when the array finishes playing, it repeats the first song. Any idea why? I am going insane because I cant figure it out...

Code below in the link: https://jsfiddle.net/wt2joay4/

var song1 = $('#sound-1');
var song2 = $('#sound-2');
var song3 = $('#sound-3');

var audioArray = [song1, song2, song3];
var i=0;
var lastPlayedFile = null;
$(".click").click(function(){
  if(lastPlayedFile !== null) {
     lastPlayedFile[1].currentTime = 0;
     lastPlayedFile.trigger('pause'); 
  }
  if (i< audioArray.length){
     lastPlayedFile = audioArray[i];
     audioArray[i].trigger('play');
     i++;
} else if (i>=audioArray.length){
     i = 0;
     lastPlayedFile = audioArray[0];
     audioArray[i].trigger('play');
  };
});

Thanks!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The issue is with i=0. This should be i=1.

The i variable is used to indicate which song to play next rather than current index.

So in i<audioArray.length it plays audioArray[i] and then does i++.

But in i>=length it plays audioArray[0] but leaves i pointing at 0, so the next played is again 0.

The fix is to leave i=1 after re-looping. This could use the same concept as above: i=0; ...play [i]...; i++; or just i=1.

} else if (i>=audioArray.length){
     lastPlayedFile = audioArray[0];
     audioArray[i].trigger('play');
     i = 1;
  };
});

Suggestion: Use a better variable name than i. If this was named nextIndex then nextIndex=0 would be clear(er) that it's going to play 0 next (when it's already playing 0).

Alternative suggestion: Keep i as the current index and increase before starting the next, eg:

var song1 = $('#sound-1');
var song2 = $('#sound-2');
var song3 = $('#sound-3');

var audioArray = [song1, song2, song3];
var i = -1;
$(".click").click(function() {

  if (i >= 0) {
    audioArray[i].currentTime = 0;
    audioArray[i].trigger('pause');
  }

  i++;
  if (i >= audioArray.length)
    i = 0;

  audioArray[i].trigger('play');
});

(and change i to currentIndex, but left as i above to compare with original)

updated fiddle

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!