If you're working with Javascript and need to control timing, your best bet is using setTimeout/setInterval. These functions are the primary mechanisms for managing time intervals in JS, although there aren't really any more advanced options available unless you want to use helper functions like 'delay' that simply wrap setTimeout/setInterval.
That being said, dmi3y's answer is accurate. However, given that you mentioned Backbone in both the tags and description, here's a more Backbone-oriented approach...
var YourModelClass = Backbone.Model.extend({url: remoteUrl});
var instance = new YourModelClass();
var seconds = 5;
window.setInterval(_.bind(instance.fetch, instance), 1000 * seconds);
Alternatively, if you prefer to incorporate it into your class definition...
var YourModelClass = Backbone.Model.extend({
url: remoteUrl,
initialize: function() {
var seconds = 5;
window.setInterval(_.bind(this.fetch, this), 1000 * seconds);
}
});
var instance = new YourModelClass();
Additionally, don't forget that setInterval returns an object that can be used with clearInterval to halt the polling process.
P.S. In case you're not familiar with _.bind
, it's part of the Underscore library which Backbone relies on, so you already have it. Its purpose is to set the value of this
within a function call, ensuring that when your timeout/interval function executes, the this
context inside will correspond to the second argument passed to _.bind
(and not just default to window
as it normally would).