Added JavaScript launch and reset button

I want to use the following so that the code starts only with the click of a button, and not the code that starts on its own when the page loads. also adding a reset button.

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var interval;
    var minutes = 5;
    var seconds = 10;
    window.onload = function() {
        countdown('countdown');
    }

    function countdown(element) {
        interval = setInterval(function() {
            var el = document.getElementById(element);
            if(seconds == 0) {
                if(minutes == 0) {
                    alert(el.innerHTML = "countdown over!");                    
                    clearInterval(interval);
                    return;
                } else {
                    minutes--;
                    seconds = 60;
                }
            }
            if(minutes > 0) {
                var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
            } else {
                var minute_text = '';
            }
            var second_text = seconds > 1 ? 'seconds' : 'second';
            el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + ' remaining';
            seconds--;
        }, 1000);
    }
</script> 
</head>

<body>
<div id='countdown'></div>
</body>
</html>
+3
source share
4 answers

instead of onload use this

<input type="button" onclick="countdown('countdown');" value="Start" />

to reset use this

<input type="button" onclick="minutes=5;seconds=10;" value="Reset" />
+3
source

The code that starts the countdown is here:

window.onload = function() {
    countdown('countdown');
}

instead, you can remove this and the built-in button in content that triggers a countdown with onclick behavior:

<a href="javascript:void(0);" onclick="countdown('countdown')">Click Me to Start</a>

The timer is stored in

var interval;

To stop it, you can enter another button that calls clearInterval (interval):

<a href="javascript:void(0);" onclick="clearInterval(interval)">Click Me to Stop</a>

In reset, do what others have suggested and save the new value in minutes, seconds :)

+3
source

:

<input type="button" value="reset" id="reset" />
<input type="button" value="start" id="start" />

javascript :

var reset = document.getElementById('reset');
reset.onclick = function() {
    minutes = 5;
    seconds = 10;
    clearInterval(interval);
    interval = null;
}

var start = document.getElementById('start');
start.onclick = function() {
    if (!interval) {
        countdown('countdown');
    }
}

+1

= 60;

You need to reset seconds to 59, because otherwise you count 60 twice. Once from 0 and once from 60.

0
source

All Articles