Audio player slows down and hangs up after playing ten songs

3

I'm doing a music player in jQuery / JavaScript / HTML5 and this is going well, but when it starts to play the songs + or- in the 13th track it starts to slow down the page and it fires impossible to continue without updating the page and losing the playlist, I 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();
    });
};

Is not my first jQuery script that happens, will it be bug in jQuery or am I doing something wrong?

    
asked by anonymous 15.09.2014 / 22:13

1 answer

2

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

Over time, the audioElement element has dozens of eventlisteners.

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

Another good optimization would be to cache the common elements such as #musics and #div3a . At every execution of the readFile3 function, jQuery must look for these elements in the document, which leaves the runtime much slower.

TL; DR

  • Evenlisteners are very costly, use as little as possible
  • Avoid running unnecessary jQuery selectors
23.10.2014 / 18:09