Skip to Content

 

Using an interval is a way to refresh your data model without refreshing the whole DOM. The DOM is the Document Object Model, or the model of your webpage the browser creates.

The setInterval function allows you to define a function or expression to execute on the specified interval. The first parameter is the function; the second is the interval in milliseconds. It is important to only call the setInterval function once. Otherwise, the amount of function calls will exponentially increase, which is BAD.

setInterval(
    /* function or expression to execute */, 
    /* interval in ms */
);

I would recommend create the function that updates your model or refreshes the data on your DOM outside of the setInterval function. In the function, you can call the method to update your model. Don’t forget to save the state of this before calling setInterval. The interval is set in milliseconds, so choose the amount of time that makes sense for you. For intensive data updates on the client side, you might want to have a longer interval. If you are handling all the data manipulation on the server side, you can have a smaller interval. Intervals do play into performance on the client side, so always be careful and considerate when using them.

modelServices: function() {
      var self = this;
      this.intervalHandle = setInterval(function() { 
          self.callYourFunction();
       },  30000);
}

I call my modelServices function which sets off the interval in my onInit function or after I set up the DOM. It depends on your use case. Whenever it’s appropriate to initiate your interval, call the modelServices function.

this.modelServices();

It is also important to clean up after yourself, so to speak. When your application or page the interval is on is closed, exiting, or being navigated away from, you’ll want to make sure you clear the interval so you aren’t using DOM resources when the DOM isn’t valid. You can do this on the standard onExit function.

onExit:function() {
   // You should stop the interval on exit. 
   // You should also stop the interval if you navigate out of your view and start it again when you navigate back. 
   if (this.intervalHandle) 
      clearInterval(this.intervalHandle) ;
} 

When using intervals, it is important to be conscience about the resources you are using on the client. Use intervals responsibly!

To report this post you need to login first.

1 Comment

You must be Logged on to comment or reply to a post.

Leave a Reply