Kamil Kamil - 5 months ago 17
Javascript Question

javascript countdown just a little timer not working

<!doctype HTML>
<html>
<head>
<title>timer</title>
<script>
function timer(button){
var btn = document.getElementById("button1").value;
var status;
if(btn == "Start"){
button.value = "Stop";
status = true;
};
if(btn == "Stop"){
button.value = "Start";
status = false;
};
var time = document.getElementById("numberinput").value;

time = ++time;
decrement();
function decrement(){
if(time > 0 && btn == "Start" && status == true){
time = --time;
document.getElementById("result").innerHTML = time;
var to = setTimeout(decrement, 1000);
};
};
};

</script>
</head>
<body>
<center>
<div id="info">Enter the number of secounds</div>
<form id="form1">
<input type="number" id="numberinput"><br />
<input type="button" id="button1" onclick="timer(this)" value="Start">
<div id="result"></div>
</form>
</center>
</body>




Why do this code does this code not work?

It should be a time that counts down.

The start button works right but the stop doesn't.

I would be really helpful if someone could explain to me why this isn't working and give me an example on how to solve this.

thanks!

Answer

You were on the right track, but had some general coding practices wrong.

  • time = --time; can be written as time--; (same for ++)
  • I would personally not declare functions inside of functions (decrement())
  • Send values as parameters to other functions
  • setTimeout() needs to have its first parameter as an anonymous function (little weird, but needs to happen)

Here is your working code:

window.timer = function(button){
    var btn = document.getElementById("button1").value;
    var status;
    if(btn == "Start"){
        button.value = "Stop";
        status = true;
    };
    if(btn == "Stop"){
        button.value = "Start";
        status = false;
    };
    var time = document.getElementById("numberinput").value;
    document.getElementById("result").innerHTML = time;
    decrement(time, status);
};

window.decrement = function(time, status){
    var btn = document.getElementById("button1").value;
    if(time > 0 && btn == "Stop" && status == true){
        time--;
        document.getElementById("result").innerHTML = time;
        var to = setTimeout(function() {
            decrement(time, status);
        },1000);
     };
 };

JSFiddle: https://jsfiddle.net/8fmn4src/

Comments