Timer in Javascript does not start

Asked

Viewed 109 times

2

I have the following situation, days ago I created a timer with some conditions and everything right. But now I need to call the function more than once, because the timer will run independently for each item coming from the database.

So I’m spending time and item number that in case will be next to id.

I put an Alert to see if was receiving the values and is , but the timer does not start, I am not able to see the error.

var segundosRestantes;
var down; 
var totalSeconds = 0;

//countDown timer
function countDown(itemX){

var item = itemX;
  
// pega a área do tempo
var timeDisplay = document.getElementById('time'+item);

	// transforma os segundos em mm: ss
	var min = Math.floor(segundosRestantes / 60);
	var sec = Math.floor(segundosRestantes - (min * 60));

	//adiciona um 0 à esquerda (como um valor de sequência) se segundos inferiores a 10
	if (sec < 10) {
		sec = "0" + sec;
	}
	if (min < 10) {
		min = "0" + min;
	}

	// concatenar com dois pontos
	var message = min.toString() + ":" + sec.toString();

	//agora mude a exibição 
	timeDisplay.innerHTML = message;

 
if(segundosRestantes > 0){
		$("#time"+item).addClass("pulseGreen"); 
	}
 
if(segundosRestantes <= 120 && segundosRestantes > 0){
		$("#time"+item).addClass("pulseYellow"); 
	}
  
  	if(segundosRestantes <= 10 && segundosRestantes > 0){
		$("#time"+item).addClass("pulsered"); 
	}

	// quando o temporizador chegar a zero
	if (segundosRestantes === 0){
		clearInterval(down);
 $("#time"+item).removeClass("pulseYellow"); 
$("#time"+item).removeClass("pulsered");  
$("#time"+item).removeClass("pulseGreen");  
    
 $("#time"+item).addClass("nopulse");    
    //stopCountdown();
	}

	//subtrair dos segundos restantes
	segundosRestantes--;

}


function startCountdown(minutos,item){
  
	totalSeconds = 0;
  clearInterval(down);
	var item = item;
  var minutes = minutos;	//recebe minutos
  //alert('item='+item+' min '+minutes);
	
	// verifica se foi informado os minutos
	if (isNaN(minutes)||minutes == ""||minutes==null){
		document.getElementById('time'+item).innerHTML='--:--';
		return; // para a função caso verdadeira
	}

	segundosRestantes = minutes * 60;
	down = setInterval(countDown(item), 1000);
	
}
#timeClock{
	position:relative;
	font-size:14px;
	margin:0 auto; 
}
#timeClock{
	float:left;
}

#minutes{
	width:80%;
	position:absolute;
	left:50%;
	top:50%;
	transform:translate(-50%,-50%);
	font-size:1.5em;
	padding:10px;
	margin-right:10px;
	text-align:center;
	max-width:400px;
}

.nopulse{
  background: grey;
  color: white;
  padding: 2px 4px 2px 4px;
  border-radius: 2px;
 }

.pulseGreen{
  background: green;
  color: white;
  padding: 2px 4px 2px 4px;
  border-radius: 2px;
 }

.pulseYellow{
	background: #ff9900;
  color: white;
  position:relative;
	padding: 2px 4px 2px 4px;
  border-radius: 2px;
  animation: pulse 0.5s linear infinite;
}

.pulsered{
	background: red;
  color: white;
  padding: 2px 4px 2px 4px;
  border-radius: 2px;
  animation: pulse 0.5s linear infinite;
}
@keyframes pulsered{
  0%{font-size:100%;}
  50%{font-size:110%;}
  100%{font-size:100%;}
}

.pulseStop{
	background: red;
  color: white;  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>

</head>

<!--Count Down-->
<span id="time1" class="nopulse timeClockInput">00:00</span>
<script>	setTimeout('startCountdown(20,1)',1000);
</script> 
<br>
<br>
<!--Count Down-->
<span id="time2" class="nopulse timeClockInput">00:00</span>
<script>	setTimeout('startCountdown(18,2)',1000);
</script> 
<br>
<br>
<!--Count Down-->
<span id="time3" class="nopulse timeClockInput">00:00</span>
<script>	setTimeout('startCountdown(13,3)',1000);
</script>

Example of my first version: https://codepen.io/aquiles-maior/pen/qBBNaXw

  • I was able to redo the code using jquery Countdown. Simply amazing this lib. Whoever needs, solution ta aqui ó: https://codepen.io/aquiles-maior/pen/WNoGMx

1 answer

3


Your code has two basic problems:

  • Using the same variable to control 3 different timeouts;
  • He’s making the call to setInterval stopping parameters in a way that doesn’t work.

For the first item, you can fix the problem by declaring 3 variables: var down1, down2, down3;

In Function, as you receive the item per parameter, you need to take the variable dynamically. To do this, you can use the window["nome-da-variavel"], then you can dynamically assemble the name, so:

var downName = 'down' + item;
clearInterval(window[downName]);

The second point, declare the passage of parameters within a function that will work, so:

setInterval( function() { countDown(item); }, 1000 );

Here your code with the changes:

var segundosRestantes;
var down1, down2, down3;
var totalSeconds = 0;

//countDown timer
function countDown(itemX) {
    var item = itemX;

    // pega a área do tempo
    var timeDisplay = document.getElementById('time' + item);

    // transforma os segundos em mm: ss
    var min = Math.floor(segundosRestantes / 60);
    var sec = Math.floor(segundosRestantes - (min * 60));

    //adiciona um 0 à esquerda (como um valor de sequência) se segundos inferiores a 10
    if (sec < 10) {
        sec = "0" + sec;
    }
    if (min < 10) {
        min = "0" + min;
    }

    // concatenar com dois pontos
    var message = min.toString() + ":" + sec.toString();

    //agora mude a exibição 
    timeDisplay.innerHTML = message;


    if (segundosRestantes > 0) {
        $("#time" + item).addClass("pulseGreen");
    }

    if (segundosRestantes <= 120 && segundosRestantes > 0) {
        $("#time" + item).addClass("pulseYellow");
    }

    if (segundosRestantes <= 10 && segundosRestantes > 0) {
        $("#time" + item).addClass("pulsered");
    }

    // quando o temporizador chegar a zero
    if (segundosRestantes === 0) {
        clearInterval(down);
        $("#time" + item).removeClass("pulseYellow");
        $("#time" + item).removeClass("pulsered");
        $("#time" + item).removeClass("pulseGreen");

        $("#time" + item).addClass("nopulse");
        //stopCountdown();
    }

    //subtrair dos segundos restantes
    segundosRestantes--;

}


function startCountdown(minutos, item) {

    var downName = 'down' + item;
    totalSeconds = 0;
    clearInterval(window[downName]);
    var item = item;
    var minutes = minutos; //recebe minutos
    //alert('item='+item+' min '+minutes);

    // verifica se foi informado os minutos
    if (isNaN(minutes) || minutes == "" || minutes == null) {
        document.getElementById('time' + item).innerHTML = '--:--';
        return; // para a função caso verdadeira
    }

    segundosRestantes = minutes * 60;

    window[downName] = setInterval(function() {
        countDown(item);
    }, 1000);

}
#timeClock{
	position:relative;
	font-size:14px;
	margin:0 auto; 
}
#timeClock{
	float:left;
}

#minutes{
	width:80%;
	position:absolute;
	left:50%;
	top:50%;
	transform:translate(-50%,-50%);
	font-size:1.5em;
	padding:10px;
	margin-right:10px;
	text-align:center;
	max-width:400px;
}

.nopulse{
  background: grey;
  color: white;
  padding: 2px 4px 2px 4px;
  border-radius: 2px;
 }

.pulseGreen{
  background: green;
  color: white;
  padding: 2px 4px 2px 4px;
  border-radius: 2px;
 }

.pulseYellow{
	background: #ff9900;
  color: white;
  position:relative;
	padding: 2px 4px 2px 4px;
  border-radius: 2px;
  animation: pulse 0.5s linear infinite;
}

.pulsered{
	background: red;
  color: white;
  padding: 2px 4px 2px 4px;
  border-radius: 2px;
  animation: pulse 0.5s linear infinite;
}
@keyframes pulsered{
  0%{font-size:100%;}
  50%{font-size:110%;}
  100%{font-size:100%;}
}

.pulseStop{
	background: red;
  color: white;  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>

</head>

<!--Count Down-->
<span id="time1" class="nopulse timeClockInput">00:00</span>
<script>	setTimeout('startCountdown(20,1)',1000);
</script> 
<br>
<br>
<!--Count Down-->
<span id="time2" class="nopulse timeClockInput">00:00</span>
<script>	setTimeout('startCountdown(18,2)',1000);
</script> 
<br>
<br>
<!--Count Down-->
<span id="time3" class="nopulse timeClockInput">00:00</span>
<script>	setTimeout('startCountdown(13,3)',1000);
</script>

  • Damn man that explanation top, thank you brother!!! I tested the Function Countdown and now it’s getting it right, and now the counter starts, but it’s mixing some information.

  • cool, don’t forget to mark the answer if it helped your problem. qto to get crazy, what do you mean?

Browser other questions tagged

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