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( ) 只执行函数一次