Hussain
Hussain

Reputation: 1

Javascript: Automatically clicking a button when countdown is complete

I am trying to display the alert message when the countdown is complete, I am trying the following code but its does not work please help!

<!DOCTYPE html>
<html>
<body>

<p id=count></p>

<form>  
  <button id="autoClickBtn" onclick="autoClick()">Click me</button>
</form>

<script>

function autoClick(){alert("I am loaded and automatically clicked");}
        var count = 5;  
            var interval = setInterval(function () {
                document.getElementById('count').innerHTML = count;
                count--;
                if (count === -1) {

                    clearInterval(interval); 
                    window.onload = function () { document.getElementById("autoClickBtn").click() };

                }

            }, 1000 );

</script>


</body>
</html>

Upvotes: 0

Views: 1001

Answers (1)

Abid Suleman Ahmed
Abid Suleman Ahmed

Reputation: 146

If you want to alert once after a certain time. Use setTimeout function. You can add the delay in milliseconds. In the example below I have added a delay of 2 secs.

setInterval, on the other hand, will run indefinitely again and again after time period defined

setTimeout(function () {
window.alert('This is an alert');
}, 2000);

Upvotes: 1

Related Questions