Rishi N
Rishi N

Reputation: 67

Implementing pause in timer using html js

I am trying to implement a timer using html and js. I am using setInterval() and clearInterval() for the same. Until now I have been able to do with starting and stopping the timer. The 'pause button' also does pause the timer but when resuming it again takes the time mentioned in the textbox rather than the current time value.

I guess using the value displayed in the <span> will do the work but I have not been able to find how to make it work..

Below is the code on which I am currently working

<html>
  <body>
    <input type="number" id="tb1"></br></br>
    <span id="mins">0 </span>
    <span>:</span>
    <span id="secs">0 </span></br></br>
    <button id="start" onclick="javascript:onStart()">start</button>
    <button id="pause" onclick="javascript:onPause()">pause</button>
    <button id="stop" onclick="javascript:onStop()">stop</button>
  </body>
</html>

.js

var mintb;
var mins;
var secs=0;
var inter;

function onStart(){
  mintb = document.getElementById("tb1").value;
  mins=parseInt(mintb);
  document.getElementById("mins").innerHTML = mins;
  inter = setInterval(timer,1000);
}

function onPause(){
  clearInterval(inter);
  console.log(mins);
  console.log(secs);
  
}

function onStop(){
  clearInterval(inter);
   mins=0;
   secs=0;
   document.getElementById("mins").innerHTML = mins;
   document.getElementById("secs").innerHTML = secs;
   
}

function timer(){
    document.getElementById("mins").innerHTML = mins;
    document.getElementById("secs").innerHTML = secs;
    secs = secs-1;
    if(secs<0){
    secs=59;
    mins=mins-1;
    console.log(mins);
    }
  
    if(mins<0){
      clearInterval(inter);
      document.getElementById("mins").innerHTML = 00;
      document.getElementById("secs").innerHTML = 00;
    }
}

Edit: tmins was written by mistake in the last if, it is actually mins

Upvotes: 2

Views: 344

Answers (2)

Sanmeet
Sanmeet

Reputation: 1410

Your code was correct

html 

<button id="resume" onclick="javascript:onResume()">Resume</button>

Js 

function onResume(){
     inter = setInterval(timer , 1000);
}

Without changing markup

function onPause() {
  clearInterval(inter);
  let button = document.querySelector('#pause')
  button.innerText = "Resume";
  button.setAttribute('onclick', 'onResume()');
}
function onResume() {
  let button = document.querySelector('#pause')
  button.innerText = "Pause";
  button.setAttribute('onclick', 'onPause()');
  inter = setInterval(timer, 1000);
}

Upvotes: 1

Aniket K
Aniket K

Reputation: 434

clearInterval clears the interval and resets the timer to 0.

You can refer this if you want to implement play and pause functionality - https://gist.github.com/ncou/3a0a1f89c8e22416d0d607f621a948a9

Upvotes: 0

Related Questions