How to make a countdown with javascript?

Asked

Viewed 12,823 times

11

Hello guys I don’t understand practically anything Javascript, so for weeks I was trying to make a script that did the following:

                                  00:00:00

1º start a countdown of 20 minutes after clicking a link.

2º And at the same time redirect to a site.

3º when passing the 20 minutes the clock would be at zero so 00:00:00 so that the user click and start counting again and redirect to post click site.

(Remember that redirects after the click and not after finishing the count!)

4º And had cookies to continue counting even after updating the page!

I couldn’t do that, but I found a script that does almost everything listed above. The only problem with the script is that it doesn’t have the link to click and start counting and doesn’t even have the cookie code to continue even after refreshing the page! Check the code below and if you know what I can do to put the link to be clicked and the cookie code

<html><head>	<script language="javaScript">	
	var min, seg;		min = 20;		seg = 1		
	function relogio(){			
		if((min > 0) || (seg > 0)){				
			if(seg == 0){					
				seg = 59;					
				min = min - 1	
			}				
			else{					
				seg = seg - 1;				
			}				
			if(min.toString().length == 1){					
				min = "0" + min;				
			}				
			if(seg.toString().length == 1){					
				seg = "0" + seg;				
			}				
			document.getElementById('spanRelogio').innerHTML = min + ":" + seg;				
			setTimeout('relogio()', 1000);			
		}			
		else{				
			document.getElementById('spanRelogio').innerHTML = "00:00";			
		}		
	}	
</script></head><body style="font-family:verdana;font-size:10px;" onLoad="relogio()">	<span id="spanRelogio"></span></body></html>


People I gave a change in the script and manage to put the link, but it turns out that after finishing the count it gets stuck at 00:00 and clicking again does not restart the count (I changed to 1 minute to be faster) see

		<script language="javaScript">	
			var min, seg;		min = 1;		seg = 1		
			function relogio(){			
				if((min > 0) || (seg > 0)){				
					if(seg == 0){					
						seg = 59;					
						min = min - 1	
					}				
					else{					
						seg = seg - 1;				
					}				
					if(min.toString().length == 1){					
						min = "0" + min;				
					}				
					if(seg.toString().length == 1){					
						seg = "0" + seg;				
					}				
					document.getElementById('spanRelogio').innerHTML = min + ":" + seg;				
					setTimeout('relogio()', 1000);			
				}			
				else{				
					document.getElementById('spanRelogio').innerHTML = "00:00";			
				}		
			}	
		</script>	
	<a href="/" onClick="relogio(event)" target="_blank">Clique Aqui</a>
	
	<span id="spanRelogio"></span>

  • 1

    Change "span" to an "a" and put "href".. and the link problem is solved ;)

  • 1

    Dude I did it, only the countdown itself became the link and also the counter was already starting itself. Then in order for the counter not to become a link I put the link below that way: <a id="spanRelogio" href="http://answall.com/" onClick="clock(Event)" target="_Blank">Click Here</a> But still the counter started alone take the test

  • 1

    i took onload="clock() and put <a id="spanRelogio" href="http://answall.com/" onClick="clock(Event)" target="_Blank">Click Here</a> ta almost the way I want :)

  • Hi @Marcio.Sx your question has been answered, it worked there?

4 answers

1

I made some changes to your code. Have a look:

Obs: To test the code. save it and test it on your local server. Otherwise the cookie will not work!

<script language="javaScript">	
'use strict'
			var min = 1,
				seg = 1;

			function start() {

				if((min == 1) && (seg == 1)){
					relogio()
				}
			}

			function relogio(){		

				if((min > 0) || (seg > 0)){				
					if(seg == 0){					
						seg = 59;					
						min = min - 1	
					}				
					else{					
						seg = seg - 1;				
					}				
					if(min.toString().length == 1){					
						min = "0" + min;				
					}				
					if(seg.toString().length == 1){					
						seg = "0" + seg;				
					}				
					document.getElementById('spanRelogio').innerHTML = min + ":" + seg;				
					setTimeout('relogio()', 1000);		
					setCookie('tempo',min + ":" + seg,30)
				}			
				else{				
					document.getElementById('spanRelogio').innerHTML = "00:00";		
					min = 1;
					seg = 1;	
				}		
			}	

			function setCookie(cname,cvalue,exdays) {
			    var d = new Date();
			    d.setTime(d.getTime() + (exdays*24*60*60*1000));
			    var expires = "expires=" + d.toGMTString();
			    document.cookie = cname+"="+cvalue+"; "+expires;
			}

			function getCookie(cname) {
			    var name = cname + "=";
			    var ca = document.cookie.split(';');
			    for(var i=0; i<ca.length; i++) {
			        var c = ca[i];
			        while (c.charAt(0)==' ') {
			            c = c.substring(1);
			        }
			        if (c.indexOf(name) == 0) {
			            return c.substring(name.length, c.length);
			        }
			    }
			    return "";
			}

			function checkCookie() {

			    var cookie = getCookie("tempo");

			    if ( cookie != "" ) {

					var tempo = getCookie('tempo').split(':');
					min = tempo[0];
					seg = tempo[1];

					relogio();
			    } 

			}
		</script>	

		<body onload="checkCookie()">
	<a href="/" onClick="start()" target="_blank">Clique Aqui</a>
	
	<span id="spanRelogio"></span>

	<body>

Explanation:

I fixed your problem of always calling clock() function. I created a function called start() that checks whether the clock() has already been called.

For the use of the cookie, I followed the documentation from: w3schools

Take a look at the code and any questions feel free to ask! ;)

1

   ***** ON Pure javascript *****

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 5,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};




***** On JQUERY *****


function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(minutes + ":" + seconds);

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

jQuery(function ($) {
    var fiveMinutes = 60 * 5,
        display = $('#time');
    startTimer(fiveMinutes, display);
});

0

var aa = 2020
var mm = 06
var dd = 07
var hh = 17
var mi = 00

function definircontagemregressiva(ano, mes, dia, horas, minutos) {
  yr = ano;
  mo = mes;
  da = dia
}
definircontagemregressiva(aa, mm, dd)


var ocasiao = "Casamento"
var message_on_ocasiao = "É HOJEEEEEE!!!"


var contagemRegressiva_largura = '510px'
var contagemRegressiva_altura = '200px'
var contagemRegressiva_color = '#ccffe1'
var abrirtags = '<font face="Verdana" size="5" color="#000000">'
var fechartags = '</font>'


var mesArray = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
var contagemcruzada = ''

function start_countdown() {
  if (document.layers)
    document.contadorRegressivo_main.visibility = "show"
  else if (document.all || document.getElementById)
    contagemcruzada = document.getElementById && !document.all ? document.getElementById("countdownie") : countdownie
  countdown()
}

if (document.all || document.getElementById)
  document.write('<span id="countdownie" style="width:' + contagemRegressiva_largura + '; background-color:' + contagemRegressiva_color + '"></span>')

window.onload = start_countdown


function countdown() {
  var today = new Date()
  var todayy = today.getYear()
  if (todayy < 1000)
    todayy += 1900
  var todaym = today.getMonth()
  var todayd = today.getDate()
  var todayh = today.getHours()
  var todaymin = today.getMinutes()
  var todaysec = today.getSeconds()
  var todaystring = mesArray[todaym] + " " + todayd + ", " + todayy + " " + todayh + ":" + todaymin + ":" + todaysec
  futurestring = mesArray[mo - 1] + " " + da + ", " + yr
  dd = Date.parse(futurestring) - Date.parse(todaystring)
  dday = Math.floor(dd / (60 * 60 * 1000 * 24) * 1)
  dhour = Math.floor((dd % (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1)
  dmin = Math.floor(((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1)
  dsec = Math.floor((((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1)

  //-----------Se no dia da ocasião-----------//

  if (dday <= 0 && dhour <= 0 && dmin <= 0 && dsec <= 1 && todayd == da) {
    if (document.layers) {
      document.contadorRegressivo_main.document.countdownnssub.document.write(abrirtags + message_on_ocasiao + fechartags)
      document.contadorRegressivo_main.document.countdownnssub.document.close()
    } else if (document.all || document.getElementById)
      contagemcruzada.innerHTML = abrirtags + message_on_ocasiao + fechartags
    return
  }

  //---------Se passou dia da ocasião-----------//
  else if (dday <= -1) {
    if (document.layers) {
      document.contadorRegressivo_main.document.countdownnssub.document.write(abrirtags + "ocasiao already passed! " + fechartags)
      document.contadorRegressivo_main.document.countdownnssub.document.close()
    } else if (document.all || document.getElementById)
      contagemcruzada.innerHTM = abrirtags + "Já passou" + fechartags
    return
  }

  //----------Caso contrário, se ainda não-----------//
  else {
    if (document.layers) {
      document.contadorRegressivo_main.document.countdownnssub.document.write(abrirtags + dday + " days, " + dhour + " hours, " + dmin + " minutes, and " + dsec + " " + occasion + closetags)
      document.countdowncontadorRegressivo_mainnsmain.document.countdownnssub.document.close()
    } else if (document.all || document.getElementById)
      contagemcruzada.innerHTML = abrirtags + dday + " dias, " + dhour + " horas, " + dmin + " minutos e " + dsec + " segundos para o <b>" + ocasiao + fechartags
  }
  setTimeout("countdown()", 1000)
}

-2

const daysIni = 2; 
const hoursIni = 23; 
const minutesIni = 59; 
const secondsIni = 59; 

startTimer(daysIni , hoursIni, minutesIni, secondsIni ) {

        let seconds = secondsIni;
        let minutes = minutesIni;
        let hours = hoursIni;
        let days = daysIni;
    
        setInterval(() => { 
          seconds--;
          if (seconds < 0) { 
            seconds = 59; 
            minutes--;
            if (minutes < 0) { 
              minutes = 59; 
              hours--;
              if (hours < 0) { 
                hours = 23; 
                days--;
              }
            }
          }
    
          let timer  = days.toString() + 'dias : ' + hours.toString().padStart(2, '0') + 'hs : ' + minutes.toString().padStart(2, '0') + 'min : ' + seconds.toString().padStart(2, '0') + 's ';
        }, 1000);

          document.getElementById('spanRelogio').innerHTML = timer; 
    
    }
    
    }

Browser other questions tagged

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