Home > Net >  recursive setTimeout() function not repeating in javascript
recursive setTimeout() function not repeating in javascript

Time:02-24

My setTimeout() function is not repeating after the initial one runs. It runs initially in the "Window.onload" but the second setTimeout() inside the "myHandler" function does not run

problem area: var timeout;

        window.onload = function(){
   timeout = setTimeout(myHandler, 5000);
};

function myHandler() {
    i  ;
   timeout = setTimeout(myHandler, 10000)
}   

full code in HTML:

<html>
<body>
    <iframe id="myVideo" allowfullscreen="true" height="720"
    width="1280"></iframe>
    

    <script type="text/javascript">

        var videoSource = new Array();
        videoSource[0] = 'xxx';
        videoSource[1] = 'xxx';

        var i = 0; 
        var videoCount = videoSource.length;
        var timeout;

        window.onload = function(){
   timeout = setTimeout(myHandler, 5000);
};

function myHandler() {
    alert('run')
    i  ;
    if (i == (videoCount - 1)) {
        i = 0;
        videoPlay(i);
    } else {
        videoPlay(i);
    }
     
    timeout = setTimeout(myHandler, 10000)
}   



function videoPlay(videoNum) {
    document.getElementById("myVideo").setAttribute("src", `${videoSource[videoNum]}&parent=localhost&autoplay=true&muted=false`);
    document.getElementById("myVideo").load();
    document.getElementById("myVideo").play();
}
videoPlay(0); // play the video


    </script>
</body>
</html>

CodePudding user response:

I ran the code locally and I got some errors on videoPlay function. I think nothing wrong on setTimeout, but when the javascript crashes, the function don't run again. Try to comment the videoPlay calls and code will run.

Consider to use setInterval instead setTimeout. And you don't need to call videoPlay on if and else, you can refact that to

if (i == videoCount - 1) 
  i = 0
videoPlay(i)

CodePudding user response:

I solved my own problem as it turns out:

document.getElementById("myVideo").load();
    document.getElementById("myVideo").play();

are not functions with iframe which was not running the rest of my code.

Thank you all for your help and input.

  • Related