Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue js triggering a method/function every x seconds

The title pretty much explains it, but i am looking to fire of a function every second.

I haven't tried anything, nor do i have much code that would be useful.

I have done some googling around and so far had n joy with any examples.

Also, i am using laravel 5.6

this doesn't work, for calling the countDown() method

export default {
    ready() {
        window.setInterval(() => {
            this.countDown();
        },1000);
    },
like image 505
The-WebGuy Avatar asked Apr 16 '18 03:04

The-WebGuy


4 Answers

The answer posted above is triggered every second (because of $nextTick) so in case you want to set a different interval, just remove the $nextTick ( In my case I set it to 30000 since I had to fire it every 30 seconds)

mounted: function () {
  window.setInterval(() => {
    this.getNotifications()
  }, 30000)
}
like image 97
Andres Paul Avatar answered Nov 16 '22 08:11

Andres Paul


Thanks guys, i found the solution, just took a bit of asking the right questions in google :)

mounted: function () {
        this.$nextTick(function () {
            window.setInterval(() => {
                this.countDown();
            },1000);
        })
    }
like image 32
The-WebGuy Avatar answered Nov 16 '22 09:11

The-WebGuy


Just to combine the solutions (since I'm unable to edit), the code below works. One gotcha is that you also want the job to stop once the view is destroyed, so you'll want to clear it when the beforeDestroy hook is called

mounted: function () {
  this.timer = setInterval(() => {
    this.countDown()
  }, 1000)
},

data() {
  return {
    timer: null
  }
},

beforeDestroy() {
  clearInterval(this.timer)
}
like image 23
giantas Avatar answered Nov 16 '22 09:11

giantas


Check this out. This one works for me.

created() {
    this.interval = setInterval(() => this.getNotifications(), 3000);
}
like image 1
Marvin Tubat Restor Avatar answered Nov 16 '22 10:11

Marvin Tubat Restor