Nastya
Nastya

Reputation: 7

JavaScript, how to set up alert , that it will appear when countdown will end

What should I change or add that alert will appear when countdown ends on 0. Now alert appears when countdown ends on 1.

    <script>
        function fn() {

        var seconds = document.getElementById("num").value;
        document.getElementById("test1").innerHTML=seconds;
      
        var countdown = setInterval(function() {
            seconds--;
            document.getElementById("test1").innerHTML=seconds;
            if (seconds <= 0) clearInterval(countdown);
            if (seconds == 0) alert("Time up!!");
        },1000);
       
        
        
        }
    

    </script>

    <p>Enter a number from 1 to 100: <br>
        <input id="num" type="text" name="number"></input>
    </p>

    <button type="button" onclick="fn()">Click me</button><br><br>

    <span id="test1"></span>

Upvotes: 0

Views: 94

Answers (1)

Sifat Haque
Sifat Haque

Reputation: 6067

Actually alert blocks all the event loop and UI. That's why other thing has to wait till alert is done with it's work.

You can use setTimeout(() => alert('Times Up!')) to solve your issue.

    <script>
        function fn() {

        var seconds = document.getElementById("num").value;
        document.getElementById("test1").innerHTML=seconds;
      
        var countdown = setInterval(function() {
            seconds--;
            document.getElementById("test1").innerHTML=seconds;
            if (seconds <= 0) clearInterval(countdown);
            if (seconds == 0) setTimeout(() => alert('Times Up!'));
        },1000);
       
        
        
        }
    

    </script>

    <p>Enter a number from 1 to 100: <br>
        <input id="num" type="text" name="number"></input>
    </p>

    <button type="button" onclick="fn()">Click me</button><br><br>

    <span id="test1"></span>

Upvotes: 1

Related Questions