Home  >  Article  >  Web Front-end  >  js implementation of refresh time every second tutorial

js implementation of refresh time every second tutorial

小云云
小云云Original
2018-01-22 09:21:263976browse

This article mainly brings you an example of using js to refresh the time every second (including year, month, day, hour, minute and second). The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor to take a look, I hope it can help everyone.

Principle: Use a timer, namely setInterval(fn,i), to execute fn every i seconds.

The specific code is given below

1. The code is as follows:

<span style="font-size:14px;"><!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>用js实现每隔一秒刷新时间(含年月日时分秒)</title>
<style>
#time{background:#33F;
   color:white;
	 height:30px;
	 line-height:30px;
	 padding:20px;
	 font-size:18px;
	 width:400px;
	 text-align:center;
	 margin:0 auto;
	 margin-top:200px;}
</style>
</head>
<body>
	<p id="time"></p>
	<script type="text/javascript"> 
	 setInterval(function(){
		 var time=new Date();
		 var year=time.getFullYear(); //获取年份
		 var month=time.getMonth()+1; //获取月份
		 var day=time.getDate();  //获取日期
		 var hour=checkTime(time.getHours());  //获取时
		 var minite=checkTime(time.getMinutes()); //获取分
		 var second=checkTime(time.getSeconds()); //获取秒
		 /****当时、分、秒、小于10时,则添加0****/
		 function checkTime(i){
			 if(i<10) return "0"+i;
			 return i;
		 }
		 var box=document.getElementById("time");
		 box.innerHTML=year+"年"+month+"月"+day+"日 "+hour+":"+minite+":"+second;		 
		},1000);   //setInterval(fn,i) 定时器,每隔i秒执行fn
</script>
</body>
</html></span><span style="font-size:32px;">
</span>

2. Rendering:

Related recommendations:

php+ajax to implement automatic page refresh time_PHP tutorial

js Example of comparing only time size

Pure JavaScript to implement real-time feedback system time code

The above is the detailed content of js implementation of refresh time every second tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn