Window setTimeout() Method - Count forever with setTimeout() - Javascript Browser Object Model

Javascript examples for Browser Object Model:Window setTimeout

Description

Window setTimeout() Method - Count forever with setTimeout()

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="startCount()">Start count!</button>
<input type="text" id="txt">
<button onclick="stopCount()">Stop count!</button>

<script>
var c = 0;/*w  w w  .  j  av a 2 s.  c  o  m*/
var t;
var timer_is_on = 0;

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

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

function stopCount() {
    clearTimeout(t);
    timer_is_on = 0;
}
</script>

</body>
</html>

Related Tutorials