Mahmoud yousif Mahmoud yousif - 4 months ago 11
Javascript Question

Using jquery button to execute JavaScript .setTimeout()

Hi Everyone I'm trying to implement a timer, that decreases in minutes and seconds based on using the .setTimeout(). Before you answer you should know, I've been on several questions and tried several implementations and nothing has worked. Below is the code:

$("#start").click(function(){

var time = workTime.text();
timer.text(time + ":00");
time *= 60000;
console.log(time);
while(time !== 0){
time -= 1000;
setTimeout(takeSec, 1000);
}
});

function takeSec(){

conosole.log("Timer Started");
var timeText = timer.text();
var minute = timeText.slice(0, timeText.indexOf(":"));
var second = timeText.slice(1);


if (second == "00") {
minute--;
timer.text(minute + ":59");
} else {
second--;
timer.text(minute + second);
}

}


Edit: Sorry I didn't explain the behavior of the code. So when the button is clicked all the about code runs, time always gets subtracted from, but setTimout(), is not working.

Answer

The logic is a little tricky but I think this jsfiddle is what you're looking for.

var btn = document.querySelector('button');
var workTime = document.querySelector('#work-time');
var timer = document.querySelector('#timer');
var timerRef, time;

btn.addEventListener("click", function () {
	clearTimeout(timerRef);
  time = +workTime.value || 0;
  timer.innerText = `${pad(time, 2)}:00`;
  time *= 60000;
  console.log(time);
	takeSec();
}, false);

function pad (num, size) { return ('000000000' + num).substr(-size); }

function takeSec () {
  console.log("taking second");
  var timeText = timer.innerText;
  var minute = timeText.slice(0, timeText.indexOf(":"));
  var second = timeText.slice(timeText.indexOf(":") + 1, timeText.length);
  console.log(timeText, minute, second);
  
  if (second == 0) {
  	minute--;
    timer.innerText = `${pad(minute, 2)}:59`;
  } else {
  	second--;
    timer.innerText = `${pad(minute, 2)}:${pad(second, 2)}`;
  }
  
  time -= 1000;
  
  if (time > 0) {
	  timerRef = setTimeout(takeSec, 1000);
  } else {
  	timer.innerText = 'DONE';
  }
}
<p id="timer"></p>

<input type="text" id="work-time">

<button>Start</button>

Comments