Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

setTimeout()

Status
Not open for further replies.

cat5ives

Programmer
Sep 13, 2011
11
0
0
US
Hi,

I have a beginner question here. I read the tutorial and from what I understand the setTimeout is only execute once after specified number of miliseconds. If that so, how can the below code keep executing (when I click the button, the timer keep counting).

Thanks in advance

<!DOCTYPE html>
<html>
<head>
<script>
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout(function(){timedCount()},1000);
}

function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}

</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()" />
<input type="text" id="txt" />
</form>
</body>
</html>

 
if that so, how can the below code keep executing (when I click the button, the timer keep counting).

Because its a recursive function.
The setTimeOut calls the timedCount() function which has the setTimeOut inside , so it calls the timedCount function again, and so on and so on.

Code:
t=setTimeout(function(){[b][COLOR=#A40000]timedCount()[/color][/b]},1000);

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top