js countdown principle and example summary

Countdown principle: use future time - current time

Future time: You can use the date object to pass parameters to get the future time. There are two forms of parameters: digital form and string form

  • new Date(2018,3,22,6,44,30) or new Date('April 22,2018 6:44:30')

Current time: just use new Date()

Precautions:

The time unit obtained by this method is milliseconds, so first convert it to seconds so that it is easy to calculate (divide by 1000), don't forget to round up the number of seconds you get (because there may be decimals)

The month is calculated from 0, so if it is to obtain the future time and month, such as April, the number we fill in should be 3, if it is to obtain the current time and month, if it is 3, then the current month is April

Supplement: We try to convert the obtained month, day, hour, minute and second into two digits. We can encapsulate it as a function, which is convenient to use. I don't use it here, but I encapsulated it before. code show as below:

function getTwo(n){
       return n<9?'0'+n:''+n ;
}

code

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Countdown</title>
<style>
.t1 { width:400px; }
</style>
<script>

/*
var t =  Math.floor( new Date().getTime()/1000 );
alert( Math.floor(t/86400)+'day'+Math.floor(t%86400/3600)+'hour'+Math.floor(t%86400%3600/60)+'minute'+t%60 +'seconds' );
*/

window.onload = function () {
	var aInp = document.getElementsByTagName('input');
	var iNow = null;
	var iNew = null;
	var t = 0;
	var str = '';
	var timer = zero;
	
	aInp[2].onclick = function () {
		iNew = new Date(aInp[0].value);
		clearInterval( timer );
		
		timer = setInterval (function (){
			
			iNow = new Date ();
			t = Math.floor ((iNew - iNow) / 1000);
			
			if ( t >= 0 ) {
				
				str = Math.floor(t/86400)+'day'+Math.floor(t%86400/3600)+'hour'+Math.floor(t%86400%3600/60)+'minute'+t%60 + 'seconds';
			
				aInp[1].value = str;
				
			} else {
				
				clearInterval( timer );
				
			}
		
		}, 1000);
	};
};
</script>
</head>

<body>

距离:<input class="t1" type="text" value="April 27,2018 22:3:0" /><br />
还剩:<input class="t1" type="text" />
<input type="button" value="Start the countdown" />

</body>
</html>


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324678290&siteId=291194637