js中setInterval与setTimeout的区别

版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/csdnluolei/article/details/83932381

一、setInterval与setTimeout的区别

1、setInterval

setInterval() 方法可按照指定的周期来调用函数(以毫秒为单位)

语法: setInterval(函数表达式,毫秒数);

setInterval() 会不停的调用函数直到clearInterval()被调用或者窗口被关闭

由 setInterval()返回的ID值可用作clearInterval()方法的参数。

2、setTimeout

setTimeout()方法用于在指定毫秒数后再调用函数(以毫秒为单位)

语法: setTimeout(函数表达式,毫秒数);

setTimeout()只执行函数一次,如果需要多次调用可以使用setInterval()

两者区别:

扫描二维码关注公众号,回复: 4029530 查看本文章

setTimeout()方法只运行一次,也就是说当达到设定的时间后就出发运行指定的代码,运行完后就结束了。

setInterval()是循环执行的,即每达到指定的时间间隔就执行相应的函数或者表达式,是真正的定时器。

二、setTimeout()

两秒钟后会弹出框

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>setInterval与setTimeout的区别</title>
		<script type="text/javascript">
			setTimeout("test()", 2000);
			function test(){alert('setTimeout("test()", 2000);')}
		</script>
	</head>
	<body>
	</body>
</html>

三、clearTimeout()

两秒钟后不会弹出框,因为被clearTimeout叫停了

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>setInterval与setTimeout的区别</title>
		<script type="text/javascript">
			var timeId = setTimeout("test()", 2000);
			function test(){alert('setTimeout("test()", 2000);')}
			clearTimeout(timeId);
		</script>
	</head>
	<body>
	</body>
</html>

四、setInterval 和 clearInterval

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>setInterval与setTimeout的区别</title>
		<script type="text/javascript">
			
			var timeId = setInterval("test()", 2000);
			
			function test(){
				var id = confirm('执行clearInterval方法?');
				if(id == true){
					
					clearInterval(timeId);
				}
			}
			
		</script>
	</head>
	<body>
	</body>
</html>

猜你喜欢

转载自blog.csdn.net/csdnluolei/article/details/83932381