最近在做项目的时候遇到了setInterval和clearInterval这两个js函数,今天特地来感悟记录下
我是在vue的项目中进行的代码,有下面两种用法
第一种:直接在setInterval中使用clearInterval
<button @click="cilck1">测试</button>
事件如下:cilck1 () {var time = setInterval(() => {console.log(111)clearInterval(time)}, 1000)},
第二种:在setInterval外面使用clearInterval
<button @click="cilck1">测试</button><button @click="cilck2">停止</button>
参数如下:data () {return {time: {}}},
事件如下:cilck1 () {this.time = setInterval(() => {console.log(111)}, 1000)},cilck2 () {clearInterval(this.time)},
第二种通过事件触发定时器停止,第一种也可以通过条件来判断停止