28

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);
    },
The-WebGuy
  • 877
  • 5
  • 12
  • 25
  • 1
    How exactly does it _"not work"_? When / where are you calling the `ready()` function? – Phil Apr 16 '18 at 03:59
  • 1
    I believe he must be having an error as this will get lost in setInterval callback. Is it ? Do you see any error in your console ? – Himanshu Singh Apr 16 '18 at 04:05
  • 2
    there is no lifecycle hook named `ready`. https://vuejs.org/v2/api/#Options-Lifecycle-Hooks – Jacob Goh Apr 16 '18 at 04:06

5 Answers5

29

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)
}
omushpapa
  • 1,663
  • 20
  • 25
22

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)
}
Andres Paul
  • 1,020
  • 16
  • 18
14

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);
        })
    }
The-WebGuy
  • 877
  • 5
  • 12
  • 25
1

Check this out. This one works for me.

created() {
    this.interval = setInterval(() => this.getNotifications(), 3000);
}
Harshit
  • 1,510
  • 19
  • 42
0

This works best as it makes sure the interval is cleared before the component is destroyed without defining anything in data.

created: function() {
  const timer = setInterval(() => {
    this.countDown();
  }, 1000);

  this.$once("hook:beforeDestroy", () => {
    clearInterval(timer);
  });
} 
Sahil Jain
  • 89
  • 1
  • 6