setInterval语法规范:

window.setInterval(调用函数,延时时间);

与setTimeout区别:

setTimeout是延时时间到了就去调用这个回调函数,只调用了一次 就结束了这个定时器。

setInterval是 每隔这个延迟时间 就去调用这个回调函数 会调用很多次 重复调用这个函数。应用在网页中的一些轮播图上。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script type="text/javascript">
			setInterval(function() {
				console.log('继续输出');
			},1000);
		</script>
	</body>
</html>

清除定时器  clearInterval()

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<button type="button" class="begin">开启定时器</button>
		<button type="button" class="stop">停止定时器</button>
		<script type="text/javascript">
			// setInterval(function() {
			// 	console.log('继续输出');
			// },1000);
			var begin = document.querySelector('.begin');
			var stop = document.querySelector('.stop'); 
			var timer = null;  //如果不在这里进行全局变量的设置 后边的stop点击事件就认不出 timer 因为timer在begin的点击事件内定义 是局部变量 
			//在函数内部定义的不带var的变量也是全局变量 因此在这里或许可以不用写var 直接timer = 。。。。
			begin.addEventListener('click', function() {
				timer = setInterval(function() {
					console.log('ni hao ma');
				}, 1000);
			});
			stop.addEventListener('click', function() {
				clearInterval(timer);
			});
		</script>
	</body>
</html>

京东倒计时例子:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			span {
				display: inline-block;
				width: 50px;
				height: 50px;
				background-color: #2F3430;
				line-height: 50px;
				text-align: center;
				color: #FFF;
				font-size: 20px;
			}
		</style>
	</head>
	<body>
		<div class="box">
			<span class="hour">
				1
			</span>
			<span class="minute">
				2
			</span>
			<span class="second">
				3
			</span>
		</div>
		<script type="text/javascript">
			var hour = document.querySelector('.hour');
			var minute = document.querySelector('.minute');
			var second = document.querySelector('.second');
			var inputTime = +new Date('2022-3-29 08:00:00');
			countDown();
			setInterval(countDown, 1000);			
			function countDown() {
				var nowTime = +new Date();
			
				var times = (inputTime - nowTime) / 1000;
				var h = parseInt(times / 60 / 60 % 24); //时
				h = h < 10 ? '0' + h: h;
				hour.innerHTML = h; //把剩余的小时给 小时黑色盒子
				var m = parseInt(times / 60 % 60); //分
				m = m < 10 ? '0' + m: m;
				minute.innerHTML = m;
				var s = parseInt(times % 60); //秒
				s = s < 10 ? '0' + s: s;
				second.innerHTML = s;
			}
		</script>
	</body>
</html>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐