Timing with setInterval in JS

Asked

Viewed 351 times

0

Guys I’m trying to make a timer, until it’s working the problem is that it only decreases the time if I keep clicking, and I need it to dimiua alone after 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 anyone can give me a hand there I thank. : D

2 answers

1


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

References:

http://www.w3schools.com/jsref/met_win_settimeout.asp http://www.w3schools.com/jsref/met_win_setinterval.asp

Example of what your code would look 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>
    <div id="timer" onclick="setInterval(timeCount, 1000)">
        <span id="time">30:00</span>
    </div>
</body>
</html>

  • See, man, that’s what/

0

You can do it like 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>

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

If you want to do it by clicking on something you can do it like this: https://jsfiddle.net/rbn988uy/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.