Timing with setInterval in JS

0

I'm trying to make a timer, until it's working, the problem is that it only slows down if I click, and I need it to go away once I click once.

  var mins = "30";
  var secs = "00";

function timeCount(){
  if (secs == "00"){
      secs = "60";
      mins -= 1;
    }
  
  i = 0;
    do {
      secs -= 01;
      i++;
    }
    while(i < secs.length);
  
  if (secs < "10"){
    secs = "0" + secs +"";
  }
   if (mins == "0"){
    console.log("acabou");
  }
  
  time = ''+ mins + ':' + secs + '';
      $("#time").html(time);
      console.log(time);
}
    
<div id="timer" onclick="setTimeout(timeCount, 3000)">
  <span id="time">30:00</span>
</div>

If someone can give me a hand there, I thank them. : D

    
asked by anonymous 21.05.2016 / 04:59

2 answers

1

The problem with your code is that you are using setTimeout. Try to modify for the setInterval that will work. Ah ... Another thing, if you want to make a timer, it would be more interesting if the interval of the setInterval fose 1000.

References:

link link

Example of what your code looks like:

var mins = "30";
var secs = "00";

function timeCount() {
  if (secs == "00") {
    secs = "60";
    mins -= 1;
  }

  i = 0;
  do {
    secs -= 01;
    i++;
  }
  while (i < secs.length);

  if (secs < "10") {
    secs = "0" + secs + "";
  }
  if (mins == "0") {
    console.log("acabou");
  }

  time = '' + mins + ':' + secs + '';
  $("#time").html(time);
  console.log(time);
}
<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script></head><body><divid="timer" onclick="setInterval(timeCount, 1000)">
        <span id="time">30:00</span>
    </div>
</body>
</html>
    
21.05.2016 / 07:02
0

You can do this:

    function pad(s) {
        return (s < 10) ? '0' + s : s;
    }
    
    function cronometro(segundos) {
        var seg = segundos % 60;
        var min = Math.floor(segundos / 60);
        document.getElementById('contador').innerHTML = [min, seg].map(pad).join(':');
        if (segundos > 0) setTimeout(cronometro, 1000, segundos - 1);
    }
    
    cronometro(180);
<div id="contador"></div>

This way you pass the number of seconds to the function and it counts ...

If you want to do something by clicking something you can do this: link

    
21.05.2016 / 08:16