Audio player slows down and hangs after playing about ten songs

Asked

Viewed 181 times

3

I’m making a music player in jQuery/Javascript/HTML5 and it’s going well, but when it starts to run the songs +or- in the 13th track starts to slow down the page and gives a "latch" and it’s impossible to continue without updating the page and losing the playlist, wanted to know what the problem with my current code...

function readFile3(file, file2){
    fileA = URL.createObjectURL(file);
    audioElement.setAttribute('src', fileA);
    audioElement.play();
    var test = $("#musics").html();

    $(audioElement).on("loadedmetadata", function () {
        var test3 = test.replace('<div class="music"><div class="bola"></div>'  + file3[file2].name + '</div>', '<div class="music2"><div class="bola2"></div>'  + file3[file2].name + '</div>');
        $("#musics").html(test3);
        $("#div3a").scrollTop(0);
        $("#div3a").scrollTop($(".music2").position().top);
    });

    $(audioElement).on("ended", function () {
        if (file2 < fill - 1) {
            $("#musics").html(test);
            file2 = file2 + 1;
            readFile3(file3[file2], file2);
        }
        else {
            $("#musics").html(test);
            audioElement.load();
        }
    });

    $(audioElement).on("timeupdate", function () {
        tempo();
        videoTimeUpdateHandler();
    });
};

It’s not my first jQuery script that happens to be a jQuery bug or I’m doing something wrong?

  • 3

    Is that all your code? Have you ever done any Profiling to see which operations consume the most CPU/RAM/Disk access?

  • @Renan, I did the Profiling on Chrome and I did not reach any conclusion, I had never used this feature...so I left the link with the player! Note: this is not the entire code...

  • 1

    It may be that it is instantiating several times some object, and leaving there, even after finalized, something like this.

1 answer

2

The main problem may be that with each music exchange you make the bind of events loadedmetadata, ended and timeupdate.

Over time the element audioElement has dozens of eventlisteners.

Think about a way to bind the event only once and use references to update the dynamic values, as in the case of the event loadedmetadata using the value of file3[file2].name. This value could be stored in a variable in the same scope of audioElement, and the function readFile3 updates this reference.

Another good optimization would be caching common elements such as #musics and #div3a. For each performance of the function readFile3 jQuery has to search for these elements in the document, which slows down the.

TL;DR

  • Evenlisteners are very expensive, use as little as possible
  • Avoid running unnecessary jQuery switches

Browser other questions tagged

You are not signed in. Login or sign up in order to post.