Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Timer

JavaScript Timer

In this post, a timer has been shown that shows the countdown, and its color/message gets changed after every specific period of time. 

Syntax:

setTimeout(function, milliseconds, parameter1, ...)

Parameter: It accepts some parameters which are specified below-

  • function: It is the function that will be executed.
  • milliseconds: It is the number of milliseconds to wait before executing the code. It is optional and its default value is zero(0).
  • parameter1: It is an additional parameter to pass to the function and it is optional.

Return Value: It returns a number representing the ID value of the timer that is set. JavaScript code that set the timer to 2 minutes and when the time is up the Page alert “times up”. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

Prerequisites: GetMinutes(), GetSeconds() and SetInterval() Method

JavaScript code to implement the timer:

Example: In this example, we will start a timer and display a message when timer stops. 

HTML




<script>
    var mins=.1;
    var secs=mins*60;
    function countdown() {
        setTimeout('Decrement()',60);
    }
    function Decrement() {
        if(document.getElementById) {
            minutes=document.getElementById("minutes");
            seconds=document.getElementById("seconds");
            if(seconds<59) {
                seconds.value=secs;
            }
            else {
                minutes.value=getminutes();
                seconds.value=getseconds();
            }
            if(mins<1) {
                minutes.style.color="red";
                seconds.style.color="red";
            }
            if(mins<0) {
                alert('time up');
                minutes.value=0;
                seconds.value=0;
            }
            else {
                secs--;
                setTimeout('Decrement()',1000);
            }
        }
    }
 
    function getminutes() {
        mins=Math.floor(secs/60);
        return mins;
    }
 
    function getseconds() {
        return secs-Math.round(mins*60);
    }
</script>
<body onload="countdown();">
    <div style="display: flex; width:80%;
                justify-content:center; padding-top: 0%;">
        Time Left ::
    </div>
    <div style="display: flex; width:80%;
                justify-content:center; padding-top: 0%;">
        <input id="minutes" type="text" style="width: 2%; border: none; font-size: 16px;
                      font-weight: bold; color: black;">
        <font size="5">
            :
        </font>
        <input id="seconds" type="text" style="width: 2%; border: none; font-size: 16px;
                      font-weight: bold; color: black;">
    </div>
</body>


Output:

 

RELATED ARTICLES

Most Popular

Recent Comments