How to every one minute reset one minute using JavaScript

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

The clearTimeout() method clears a timer set with the setTimeout() method.

we can create an simple countdown timer using javascript without any javascript library using above two function.

Every one minute reset count check below example

HTML Code

<button onclick="counterreset()">Clickme</button>
<div id="mycounter"></div>

JavaScript Code

<script>
    var i = 10;
    var myVar;
    function onTimer() {
        document.getElementById('mycounter').innerHTML = i;
        i--;
        if (i < 0) 
        {
           counterreset();
        }
        else 
        {
            myVar = setTimeout(onTimer, 1000);
        }
    }
    onTimer();

    function counterreset()
    {
        i = 10;
        clearTimeout(myVar);
        onTimer();
    }

</script>

Full Page Code Here

<!doctype html>
<html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Counter Demo</title>
    </head>
    <body>
        <button onclick="counterreset()">Clickme</button>
        <div id="mycounter"></div>
        <script>
            var i = 10;
            var myVar;
            function onTimer() {
                document.getElementById('mycounter').innerHTML = i;
                i--;
                if (i < 0) 
                {
                   counterreset();
                }
                else 
                {
                    myVar = setTimeout(onTimer, 1000);
                }
            }
            onTimer();

            function counterreset()
            {
                i = 10;
                clearTimeout(myVar);
                onTimer();
            }

        </script>
    </body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *