zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

【javascript编程思维】间隔性与延时性定时器的区别 , 如何停止定时器?

2023-04-18 15:53:48 时间

间隔性与延时性定时器的区别

间隔型定时器 setInterval(fun,time)

  1. fun为执⾏的函数
  2. time为间隔执⾏的时间,单位为毫秒,每过time时间就执⾏⼀次fun⾥⾯的代码
<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style type="text/css">

		#tim{
			width: 100px;
			height: 100px;
			background: red;
			margin: 0 auto;
		}
	</style>
</head>
<body>
	<div id="tim" ></div>
	<script type="text/javascript"> 
		// 间隔性性定时器 setInterval  每间隔三秒会执行一次
		setInterval(function(){
			alert("我是延时3秒执行的弹窗")
             console.log(1)   //控制台每个3秒输出1
		},3000)


	</script>


</body>
</html>
延时型定时器 setTimeout(fun,time)
  1. fun为执⾏的函数
  2. time为延时执⾏的时间,单位为毫秒,经过time时间后执⾏fun代码,只执⾏⼀次
<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style type="text/css">

		#tim{
			width: 100px;
			height: 100px;
			background: red;
			margin: 0 auto;
		}
	</style>
</head>
<body>
	<div id="tim" ></div>
	<script type="text/javascript">
		// 延时性定时器 setTimeout  只会执行一次
		setTimeout(function(){
			alert("我是延时3秒执行的弹窗")
		},3000)


	</script>


</body>
</html>

三秒后出现:

如何停止定时器

clearInterval 清除间隔性定时器

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style type="text/css">

		#tim{
			width: 100px;
			height: 100px;
			background: red;
			margin: 0 auto;
		}
	</style>
</head>
<body>
	<div id="tim" ></div>
	<script type="text/javascript">
		// 清除定时器
		var timer1=setInterval(function(){
			console.log("我是间隔性定时器")
			#time为延时执⾏的时间,单位为毫秒,经过time时间后执⾏fun代码,只执⾏⼀次
		},1000)
		var timer2=setTimeout(function(){
			console.log("我是延时性定时器")
			clearInterval(timer1)
            #执行了两次间隔性之后间隔性输出停止,这里在延时性里面把间隔性清除了,这里延时性输出一次后也不再输出
		},2000)
		       
	</script>

</body>
</html>

clearTimeout 清除延时性定时器(就是当这个延时性的定时器,在它的延时的时间还没到的时候,我这里执行到了一些代码做了判断,已经执行了这些代码,并且你不想在执行这个定时器的时候)

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style type="text/css">

		#tim{
			width: 100px;
			height: 100px;
			background: red;
			margin: 0 auto;
		}
	</style>
</head>
<body>
	<div id="tim" ></div>
	<script type="text/javascript">
		// 清除定时器
		var timer1=setInterval(function(){
			console.log("我是间隔性定时器")
			clearTimeout(timer2)   
			// 本来的输出是一秒输出一次间隔性,2秒一次延时性,这里清除了延时性后下面的延时性不输出,间隔性继续输出
		},1000)
		var timer2=setTimeout(function(){
			console.log("我是延时性定时器")
		},2000)
		


	</script>


</body>
</html>