vue

How to use setInterval in VueJS


In this article, you are going to learn about how to use setInterval in VueJS.

The setInterval() method lets you call a function with a fixed time delay between each call. It returns an interval ID that is used to identify the interval uniquely. This method will keep executing the particular code snippet until you call clearInterval() to stop it. Before using it in VueJs, let’s see an example of setInterval() method in JavaScript:

function greetings() {
  console.log('Good Morning!');
}

setInterval(greetings, 2000);

/*
        Output:
        Good Morning!
        Good Morning!
        .............
*/

You can see that it will keeps printing the Good Morning! while using setInterval() method until you terminate the program or use clearInterval(). But this is not our goal. We will use this setInterval() method in VueJs.

The best way to learn something is to create something by using it. We will also do the same so that you can learn how to apply things to solve real-world problems. We will create a clock that will display the current local time after 5 seconds each. To do so we will use setInterval() method in VueJS.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
 
  <title>SetInterval In VueJS</title>
</head>
<body>
  
  <div id="app">
    <h1>{{localTime}}</h1>
  </div>
  
 <script src="<https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js>"></script>
 <script src="app.js"></script>  
  
</body>
</html>

Here we have linked VueJS from CDN and right under it we linked our JavaScript file. The time will print into Heading One. Let’s see the functionality of VueJs code in the below:

VueJS:

new Vue({
  el: '#app',
  data: {
    localTime: " "
  },
  methods:{
    showLocaleTime: function () {
      var time = this;
      setInterval(function () {
       time.localTime = new Date().toLocaleTimeString();
    }, 5000);
   }
  },
 mounted () {
  this.showLocaleTime()
        }
});

Here, we take app id as element and first the data will empty and it will fill up with the data that comes from setInterval() method and shows the output as local time after 5 seconds each and it will keep updating. Let’s see the output below:

Output:

Here, you can see that the time is printing after 5 seconds delay each time. That means we’ve successfully implemented setInterval() method in our project. We add some CSS style to give it a better look. This is optional. You may style things on your own interest.

This is how you can use setInterval() method in VueJs. Now your task is to take this article as a reference and try to find more real-world usage of this seInterval() method and implement them.


Share on social media

//