0

I want to make a break in a for loop in javascript. My actually code is

<p id="1">The video opens</p>
        <script>
    for(i=0; i<5; i++) {
        myWindow = window.open("VIDEO");
        document.getElementById("1").innerHTML = "Wait";
        setTimeout(myWindow.close(), 10000);
    }

        </script>

The video should start in a new tab, plays 10 seconds, and then closes. Then it starts again, plays anozher time 10 seconds and closes the video etc... But the Timeout isn't a real timeout. It makes only the myWindow.close() comes 10 seconds later That means, all 10 videos start, and then, 10 seconds later, one video closes. How can I make it work right?

Korne127
  • 113
  • 10

2 Answers2

0

I think you're saying you want to do the ten videos one at a time.

If so, you can't use a for loop for this, you have to use either setInterval or a chained series of setTimeout. I'd go for the latter in this case:

// IIFE to keep our variables private
(function() {
    // Counter
    var i = 0;

    // Show the first video
    showVideo();

    // Function for showing the current video identified by `i`
    function showVideo() {
        var myWindow = window.open("VIDEO"); // Presumably use `i` here
        document.getElementById("1").innerHTML = "Wait";
        setTimeout(function() {
            // Close the window
            myWindow.close();

            // Done yet?
            if (++i < 10) {
                // No, show the next video
                showVideo();
            }
        }, 10000);
    }
})();
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • Why there's at the beginning a bracket ( – Korne127 Jul 24 '16 at 10:29
  • @Korne127: It's one of the standard ways of creating an inline-invoked function expression (IIFE), see [this answer](http://stackoverflow.com/a/13341710/157247) for details. If we just started with `function`, it would be a syntax error. – T.J. Crowder Jul 24 '16 at 10:37
  • I have made the whole function away and changed it a little, but it workes great! – Korne127 Jul 24 '16 at 10:42
-2

Change setTimeout with setInterval function, setInterval function is made for loop, it's run every 10 seconds e.g. like you want.

ristapk
  • 1,111
  • 2
  • 12
  • 25