0

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

1
  • i expect more than one print of test to the console , there is just one log call that will be only executed once?! Commented May 23, 2018 at 15:58

1 Answer 1

1

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)
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.