循环执行就是设置一个时间间隔,每过一段时间都会执行一次这个方法,直到这个定时器被销毁掉。前端
用法是setInterval(“方法名或方法”,“延时”), 第一个参数为方法名或者方法,注意为方法名的时候不要加括号,第二个参数为时间间隔(毫秒)。vue
this.timer = setInterval(this.updataDevice, 5000) // 第一个参数:this.updataDevice 是ts中的方法,只写方法名不写括号。 // 第二个参数:5000 表示延时,毫秒,5000毫秒=5秒,即执行完本次后,隔5秒再次执行
案例是vue写的,用vue举例:函数
beforeDestroy() { // 组件销毁前执行 clearInterval(this.timer) // 清除定时器 this.timer = null // 定时器的变量赋值null },
顺便例一下vue的生命周期函数:this
beforeCreate: function () { console.group('beforeCreate 建立前状态===============》'); }, created: function () { console.group('created 建立完毕状态===============》'); }, beforeMount: function () { console.group('beforeMount 挂载前状态===============》');//已被初始化 }, mounted: function () { console.group('mounted 挂载结束状态===============》'); }, beforeUpdate: function () { alert("更新前状态"); console.group('beforeUpdate 更新前状态===============》'); //这里指的是页面渲染新数据以前 alert("更新前状态2"); }, updated: function () { console.group('updated 更新完成状态===============》'); }, beforeDestroy: function () { console.group('beforeDestroy 销毁前状态===============》'); }, destroyed: function () { console.group('destroyed 销毁完成状态===============》'); }
定时执行setTimeout是设置一个时间,等待时间到达的时候只执行一次,可是执行完之后定时器还在,只是没有运行。code
用法是 setTimeout(“方法名或方法”, “延时”); 第一个参数为方法名或者方法,注意为方法名的时候不要加括号,第二个参数为时间间隔。生命周期
setTimeout(() => { this.showMarker() // 执行的方法 }, 1000) // 时间 1000毫秒 = 1秒