1

I have a timer, but I want to add a "STOP" button or link which it will freeze the timer. How?

HTML:

TIME LEFT: <font size="5" color='#F7D358'><span id='timer_div'></span></font>

JAVASCRIPT:

var seconds_left = 60;
var interval = setInterval(function() {
    document.getElementById('timer_div').innerHTML = --seconds_left;

    if (seconds_left <= 0)
    {
        document.getElementById('timer_div').innerHTML = '...';
        clearInterval(interval);
    }
}, 1000);

DEMO: http://jsfiddle.net/wa4ms/

Kara
  • 6,115
  • 16
  • 50
  • 57
user3148286
  • 21
  • 1
  • 2

4 Answers4

1

simply use this

<input type="button" value="STOP" onclick="clearInterval(interval);" />
Tun Zarni Kyaw
  • 2,099
  • 2
  • 21
  • 27
  • You can not resume it now! Use setTimeout instead. Example is at - http://stackoverflow.com/questions/11563382/javascript-timer-pause – Kunj Dec 31 '13 at 04:45
0

Here is at least an example on how to stop a running funciton (timer):

http://www.w3schools.com/js/tryit.asp?filename=tryjs_setinterval3

patrick
  • 881
  • 2
  • 9
  • 32
0

html:

TIME LEFT: <font size="5" color='#F7D358'><span id='timer_div'></span></font>
<input type="button" value="Pause" id="timer_pause" />
<input type="button" value="Resume" id="timer_resume" />

javascript:

var seconds_left = 60, interval;
function startTimer() {
    clearInterval(interval);
    interval = setInterval(function() {
        document.getElementById('timer_div').innerHTML = --seconds_left;

        if (seconds_left <= 0)
        {
            document.getElementById('timer_div').innerHTML = '...';
            clearInterval(interval);
        }
    }, 1000);
}
document.getElementById('timer_pause').onclick = function () {
    clearInterval(interval);
};
document.getElementById('timer_resume').onclick = function () {
    startTimer();
};
startTimer();
Eugene Kuzmenko
  • 947
  • 9
  • 11
0

http://jsfiddle.net/dpeDe/

TIME LEFT: <span id='timer_div'></span>
<button></button>

<script>
var seconds_left = 60;
var interval;
var playing = false;
var b = document.getElementsByTagName("button")[0];

function tick(){
    document.getElementById('timer_div').innerHTML = --seconds_left;
    if (seconds_left <= 0){
        document.getElementById('timer_div').innerHTML = '...';
        clearInterval(interval);
    }
}

function play(){
    interval = setInterval(tick, 1000);
    b.innerHTML = "&#x25a0; stop";
}

function pause(){
    clearInterval(interval);
    b.innerHTML = "&#x25ba; play";
}

b.onclick = function(){
    playing ? pause() : play();
    playing = !playing;
};

b.click();
</script>

P.S. the <font> tag is deprecated