javascripthowler.js

How to end interval used to call function which updates time with Howler.js


I have made a function UpdateTime(x) which updates gets the current and total time of a song and writes in inside a div.

I call this function on onload (Howler.js), so it writes 0:0/song:time when the song is loaded and on onplay (Howler.js) with an interval every 50 miliseconds so it automatically updates the time when I start playing the song.

My problem is that this will cause an endless loop and effect performance.

My question is: How do I end that endless loop when the song stops playing?

If any of you have a more elegant approach to updating the time with Howler.js I would also appreciate it.

var songname = new Howl({
    src: ['mp3/songname.mp3'],
    onload: function() {
        UpdateTime(songname);
    },
    onplay: function() {
        setInterval(function(){
            UpdateTime(songname);
        },50);
    }/*,
    onend: function() {
        maybe end the interval here?...
    }*/
});

function UpdateTime(x){
    let a = (x.seek()).toFixed();
    let a2 = Math.floor(a / 60);
    let a1 = a - a2 * 60;
    let b = (x.duration()).toFixed();
    let b2 = Math.floor(b / 60);
    let b1 = b - b2 * 60;
    document.getElementById("time").innerHTML=a2+":"+a1+" / "+b2+":"+b1;
}

Solution

  • var durationUpdater;
    
    var song = new Howl({
        // song is still missing bunch of stuff here, but irrelevant for this issue
    
        onplay: function() {
            durationUpdater = setInterval(function(){
                UpdateT1();
                console.log(currentsong + ': song-progress updated');
            },500);
        },
        onend: function() {
            clearInterval(durationUpdater);
        }
    });