ashil
ashil

Reputation: 97

How to start and stop counter by single button

I want to start counter when I click the button first time and stop when I click on second time.

I tried the following code:

var myTimer;

function clock(){
    myTimer = setInterval(myClock,1000);
    var c = 0;
    function myClock(){
        document.getElementById('demo').innerHTML = ++c;    
    }
}    
<h1>---Counter----</h1>
<p id="demo"></p>
<button onclick="clock();clearInterval(myTimer);">start</button>

I want to start the counter after the initial click of button and stop it in the second click.

Upvotes: 0

Views: 2188

Answers (2)

Always Helping
Always Helping

Reputation: 14570

You can set a flag to check if timer has started with true or false.

If the timer is started change the innerText to stop and and use the same button to start the timer again.

Live Demo:

var myTimer;

//Check if started ot not
var started = false

//Timer
var timer = 0;

//Btn text
var btn = document.getElementById("startBtn")

function clock(e) {
  if (!started) {
    myTimer = setInterval(myClock, 1000);
    started = true
    btn.innerText = 'Stop'
  } else {
    started = false
    clearInterval(myTimer);
    btn.innerText = 'Start'
  }
}

function myClock() {
  if (started) {
    ++timer
    document.getElementById('demo').textContent = timer;
  }
}
<h1>---Counter----</h1>
<p id="demo"></p>
<button id="startBtn" onclick="clock(this)">start</button>

Upvotes: 2

Sascha A.
Sascha A.

Reputation: 4626

I add an eventlistener to the button. If clicked I check if the button contains class start. If not (that's the initial) add this class, set textContent to "stop" and start the clock. Otherwise remove this class set textContent on "start" and clearInterval. Note: For clearing the interval you need to store the return of setInterval in a variable with access at clearing, so I declared it at start global.
If you press button after stop again timer will restart at beginning.

let btn = document.getElementById('btn');
var myTimer;

btn.addEventListener('click', function() {
    if (btn.classList.contains('start')) {
        btn.classList.remove('start');
        btn.textContent = "start";
        clearInterval(myTimer);
    } else {
        btn.classList.add('start');
        btn.textContent = "stop";
        clock();
    }
});

function clock(){
    function myClock(){
        document.getElementById('demo').textContent = ++c;
    }
    myTimer = setInterval(myClock,1000);
    var c = 0;
}
<h1>---Counter----</h1>
<p id="demo"></p>
<button id="btn">start</button>

Upvotes: 3

Related Questions