[英]Vuejs2 set timeout fails to execute the function after the set seconds
AM trying to execute a function after 1 second using setTimeout but it fails to work AM尝试使用setTimeout在1秒后执行功能,但无法正常工作
so i have 所以我有
mounted(){
this.getTime();
}
methods:{
getTime(){
setTimeout(()=>{
console.log("test..");
},1000)
}
}
THe above only logs once 以上仅记录一次
Ihave tried changing the arrow function in set timout to 我尝试将settimout中的箭头功能更改为
setTimeout(function(){
console.log("test")
}, 1000);
But even so it fails 但即便如此,它还是失败了
Where am i going wrong as i expect more than one print of test to the console 我要去哪里错了,因为我希望控制台可以打印多份测试
I prefer using the mounted hook as this function will perform other operations with this keyword which becomes available after mount 我更喜欢使用已挂接的钩子,因为此函数将使用此关键字执行其他操作,该关键字在挂载后可用
Use setInterval instead of setTimeout . 使用setInterval而不是setTimeout 。
setInterval
will repeat until you tell it to stop, whereas setTimeout
will only run once (unless it is canceled before it gets ran). setInterval
将重复执行直到您告诉它停止为止,而setTimeout
将只运行一次(除非在运行之前被取消)。
mounted(){
this.getTime();
},
methods:{
getTime(){
setInterval(()=>{
console.log("test..");
}, 1000)
}
}
Your other option is to call this.getTime()
again at the end of your timeout like this: 您的另一个选择是在超时结束时再次调用this.getTime()
,如下所示:
mounted(){
this.getTime();
},
methods:{
getTime(){
setTimeout(()=>{
console.log("test..");
this.getTime();
}, 1000)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.