Reputation: 6629
AM trying to execute a function after 1 second using setTimeout but it fails to work
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
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
Upvotes: 0
Views: 23
Reputation: 36299
Use setInterval instead of setTimeout.
setInterval
will repeat until you tell it to stop, whereas setTimeout
will only run once (unless it is canceled before it gets ran).
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:
mounted(){
this.getTime();
},
methods:{
getTime(){
setTimeout(()=>{
console.log("test..");
this.getTime();
}, 1000)
}
}
Upvotes: 1