JavaScript > Timer

setTimeout in JavaScript

How to create a timers using setTimeout in JavaScript?


In the previoius post, we learnt how to create a timer. In case we have implemented timer in JavaScript and want to break or stop it, we can follow this approach.

Set Timeout

Set Timeout is an method in JavaScript {setTimeout() method}, which is used to call a function or evaluate an expression after a specified intervals(Time in Milliseconds). This method executes only once and it is having three parameters, 'function', 'milliseconds', 'parameter1,parameter2,....' in this parameters 'function' and 'milliseconds' are the required parameters and last parameter is optional.

NOTE: The setTimeout() method executes the function only once, if we want to execute to the function repeatedly, we can use setInterval() method in JavaScript.

In JavaScript, by using setTimeout() method we can stop the run time.

Stop the run timer.

From the below code we shall learn how to stop the run time and how to start the stopped run time.

    <script>
        var count = 0;
        function TestFunction() {
            count++;
            document.getElementById("lblText").innerHTML = count;
            t = setTimeout("TestFunction()", 1000);
        }
        function StopCount() {
            clearTimeout(t);
        }
    </script>

    <label id="lblText">0</label>
    <input type="button" id="btnTest" onclick="TestFunction()" value="Start Timer" />
    <input type="button" id="btnStop" value="Stop Timer" onclick="StopCount()" />

In the above code snippet, we have implemented a timer using setTimeout() method that stores the tick into the t variable. This timer executes inside the “TestFunction” function that fires when the “Start Timer” button is clicked.

In the click event of “Stop Timer” button we have called the “StopCount()” function that calls clearTimeout() method by passing the t variable that stops the timer.

NOTE: The timer starts after clicking on "Start timer" button, and it will run until we click on "Stop Timer" button. Again if we click on "Start Timer" button, the timer satrts running from where it stopped.

OUTPUT

Alerting the user after 2 seconds with alert (Function inside the method).

<p>Alert the user for after 2 seconds with an alert "WARNING!"</p>
<input type="button" value="Alert" onclick="myAlert()"/>

<script>
    function myAlert() {
        setTimeout(function() { alert("WARNING!"); },2000);
    }
</script>

Alerting user after 2 seconds

In the above code snippet we have given function inside the setTimeout() for the alert. Onclick of the button "Alert" fires the function myAlert() in the <script> at the same time function() inside the setTimeout() method alerts the user after 2 seconds.

NOTE: Every onclick of the button gives only one alert after 2 seconds. If we click two times repeatedly and waited for 4 seconds, we can find two alerts (After clicking "OK" in the first alert you can find second alert with out waiting 2 seconds).

OUTPUT

Alerting the user after 2 seconds with named function.

<p>Alert the user with named function after 2 seconds with an alert "WARNING!"</p>
<input type="button" value="Alert" onclick="myName()"/>

<script>
    function myName() {
        a = setTimeout(myAlert, 2000);
    }

   function myAlert(){
       alert("WARNING!");
    }
</script>

Alert user after 2 seconds with named function

We need to alert the user with the named function, for that we named the function name as myAlert() in the <script> block. Onclick of the button gives the alert after 2 seconds.

OUTPUT

Showing the seconds in the text box.

<p>Click the below button to know the seconds of time in text box.</p>
<input type="button" value="Click Here" onclick="myText()"/>
    <input type="text" id="myId"/>

<script>
    function myText() {
        var a = document.getElementById("myId");
        setTimeout(function () { a.value = "1 seconds" }, 1000);
        setTimeout(function () { a.value = "2 seconds" }, 2000);
        setTimeout(function () { a.value = "3 seconds" }, 3000);
        setTimeout(function () { a.value = "4 seconds" }, 4000);
        setTimeout(function () { a.value = "5 seconds" }, 5000);
        setTimeout(function () { a.value = "6 seconds" }, 6000);
        setTimeout(function () { a.value = "7 seconds" }, 7000);
        setTimeout(function () { a.value = "8 seconds" }, 8000);
        setTimeout(function () { a.value = "9 seconds" }, 9000);
        setTimeout(function () { a.value = "10 seconds" }, 10000);
    }
</script>

Seconds in text box

We need to sipaly the seconds in the text box, for that we used above code snippet. Onclick of the button show first 10 seconds and stos. If we again click one the button it will start showing from 1st second upto 10 seconds. To see the output of the above code, click here.

NOTE: Click the button to start displaying the seconds.

Onclick opens a new window and closes automatically after 5 seconds.

<p>Click the below button to open a new window and wait for 5 seconds to close it automatically.</p>
<input type="button" value="Open New Window" onclick="myOpen()"/>

<script>
    function myOpen() {
        var a = window.open("", a, "width=500, height=300");
        a.document.write("<div>This is TechFunda(New Window).</div>");
        setTimeout(function () { a.close() }, 5000);
    }
</script>

Open new windo and close after 5 seconds

We need to open a new window and closes automatically after 5 seconds with the onclick of the button, for that we are using above code snippet. To observe this in the output, click here.

Stopping the alert before it display on the window.

<p>Click the "Alert" button to get the alert. <br />Click the "Stop Alert" button to stop the alert. (We must click before the alert display time on window, the alert display time is 4 seconds)</p>
<input type="button" value="Alert" onclick="myAlert()"/>
<input type="button" value="Stop Alert" onclick="myStopAlert()"/>

<script>
    var a;

    function myAlert() {
        a = setTimeout(function () { alert("TechFunda") }, 4000);
    }
     
    function myStopAlert() {
        clearTimeout(a);
    }
</script>

Stop alert before displaying on window

The above code snippet gives the output of how to stop the alert before displaying on the window. To stop the alert we used clearTimeout() and to see the output of above code snippet, click here.

Passing parameter to the myAlert function.

<p>Click the "Alert" button to get the alert after 4 seconds.</p>
<input type="button" value="Alert" onclick="myFunction()"/>
<p id="myId"></p>

<script>
    var a;

    function myFunction() {
        a = setTimeout(myAlert, 4000, "First parameter");
    }

    function myAlert(param1) {
        document.getElementById("myId").innerHTML += "WARNING!";
    }
</script>

Passing parameter to function

In the above code snippet we passed the parameter, the above code snippet gives the repeated alert on the window for every onclick.

OUTPUT

 Views: 16120 | Post Order: 189



Write for us






Hosting Recommendations