Vue.js polling using setInterval()

in Code

Vue.js polling using setInterval()

I came up with an easy way to repeat a function in Vue.js. For instance, you want to periodically retrieve data from your database using the backend API. Without any additional packages.

Javascript

To achieve that you need to use the javascript method called setInterval(). It’s a simple function that would repeat the same task over and over again. Here’s an example:

function myFunction() {
	setInterval(function(){ alert("Hello world"); }, 3000);
}

If you add a call to this method for any button and click on it, it will print Hello world every 3 seconds (3000 milliseconds) until you close the page.

First attempt using Vue.js

created () {
	setInterval(() => {
		this.$store.dispatch('RETRIEVE_DATA_FROM_BACKEND')
	}, 3000)
}

This is a good approach but the problem is — it will keep keep running after you switch to another page, because it’s a single page application.

Second attempt using Vue.js

You need to call clearInterval() method to clear the timer set in setInterval() method.

To do so you need to pass the ID value returned by setInterval() to the clearInterval() method.

Here is an example:

data () {
	return {
		polling: null
	}
},
methods: {
	pollData () {
		this.polling = setInterval(() => {
			this.$store.dispatch('RETRIEVE_DATA_FROM_BACKEND')
		}, 3000)
	}
},
created () {
	this.pollData()
}

Note how we assigned our setInterval() method to the polling object. We’re now going to pass it to the clearInterval() method.

To do that we use a function called beforeDestroy(). It’s called right before a Vue instance is destroyed. At this stage, the instance is still fully functional.

It will prevent memory leaks that setInterval() method can cause.

beforeDestroy () {
	clearInterval(this.polling)
}

This is it, we’ve just cleared the timer method and stopped polling data from the backend.

Full example

data () {
	return {
		polling: null
	}
},
methods: {
	pollData () {
		this.polling = setInterval(() => {
			this.$store.dispatch('RETRIEVE_DATA_FROM_BACKEND')
		}, 3000)
	}
},
beforeDestroy () {
	clearInterval(this.polling)
},
created () {
	this.pollData()
}

I hope it was useful. Make sure you check other Vue.js tips and tricks and know the difference between LocalStorage vs SessionStorage vs Cookies.


Subscribe to my newsletter ✌️

Subscribe


Write a Comment

Comment