How to make a timer which executes a function within a fixed time using JavaScript

Use of setTimeout function and make a count-up timer

Category: Java Script Tags: HTML, Java Script

Java Script tutorial 14

        Today I am going to show you how to make a timer which execute a function within a fixed
time using javascript.

<script type="text/javascript">
var count = 0;
function set_timer()
count ++;
var pdata = document.getElementById('p1');
pdata.innerHTML = pdata.innerHTML + '<br />Counter no: ' + count;
if(count <= 9)
count = 0;
<input type="button" onclick="set_timer()" value="Start timer" />
<p id='p1'></p>

        Above we created a button with bounded with a function set_timer() at onclick event. When user clicks on the button the function inside script is executes. we created there a counter initial value is 0 and the at first count it increments by one and set innerHTML of paragraph p1 as Counter no: 1, then it sets the timer for 500ms to execute this function again and its work like recursion till the value of count do not exceed 9 at 10th loop the else executes and set the value of Count again to 0.
        The setTimeout method takes two arguments first is the function will be execute and second
is the time after that the function will be execute.

Like 1 Person
Last modified on 29 August 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 135
Questions: 9
Given Best Solutions: 9 *


Sonia Jain
nice article ..
thank you
Like 0 People on 24 June 2013
Nikhil Joshi
thanks sonia nd u r welcome
Like 1 Person on 3 July 2013

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User