setInterval( ) VS setTimeout( )

Window setInterval( ) 方法

一秒打印一次如何实现

		<script>
			setInterval(function() {
				console.log("hello !");
			}, 1000);
		</script>
	es6 写法 :
		<script>
			setInterval(() => {
				console.log("hello !");
			}, 1000);
		</script>

这样子 会一直打印,每间隔1秒就会打印一次 ,如何让它停止打印呢?

如何停止循环

	<body>
		<script>
			var myVar;

			function startInterval() {
				myVar = setInterval(() => {//给定时器赋值 ,这个值是固定的(一般是个正整数)
					console.log("hello !",myVar);
				}, 1000);
			}

			function stopInterval() {
				clearInterval(myVar);
			}
		</script>
		<button onclick="startInterval()">点我开始</button><br />
		<button onclick="stopInterval()">点我停止</button> 
		
	</body>

Window setTimeout( ) 方法

1秒后打印 hello 。 类似于现实生活中的闹钟 ,只执行一次

	<body>
		<script>
			setTimeout(() => {
				console.log("hello !")
			}, 1000)
		</script>
	</body>

总结

两个非常常用的函数都有两个参数 函数表达式 + 毫秒数

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

setTimeout( ) 只执行函数一次

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值