"Keep an eye on the server with Backbone.js by running periodic checks

In an effort to keep my backbone application constantly checking the server for model updates, I aim to create a system similar to Twitter's auto-refresh feature for new tweets.

Currently, I am connecting to an external application through their API and do not have access to their server. This means I need to rely on client-side solutions for the checking process while also being mindful of memory usage. How can I make this happen effectively?

Answer №1

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).

Answer №2

a potential answer

(function TheShootsAreCalled(){
   console.log('who am I?'); // finding a way to communicate with the server
   window.setTimeout(TheShootsAreCalled, 1500);
})();

the reason for using setTimeout rather than setInterval is because it ensures that the next cycle will only be called once the current one is completed

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Gaining access to the isolated scope of a sibling through the same Angular directive led to a valuable discovery

I am currently working on an angularjs directive that creates a multi-select dropdown with a complex template. The directives have isolated scopes and there is a variable called open in the dropdown that toggles its visibility based on clicks. Currently, t ...

Troubleshooting ngFor in Angular 5

I'm currently working on a component that needs to display data fetched from the server. export class CommerceComponent implements OnInit { dealList; ngOnInit() { this.getDeals(); } getDeals(){ this.gatewayService.se ...

Extracting data from a JavaScript React webpage with Python Selenium, targeting an element that disappears shortly after loading

Having trouble with scraping a webpage that features a React element hiding a dropdown after a few seconds. Upon initially arriving at the page, this is what is visible and what I aim to scrape: https://i.sstatic.net/VVY4r.jpg The specific information I ...

How to change class names dynamically in Vue.js?

I am looking for a way to dynamically change the background color based on a review rating using Vue.js. Ideally, I would like to achieve this with the following code: <div class="review" :style="reviewColor(hotel.average)"> In my methods section, ...

Using HTML and JavaScript, we can set two different color values - one for the background and one for the h1 title

I am trying to save two values, one for the h1 tag and one for the body background. I want the user to select color 1 and color 2. When I press the third button, all changes should be applied and the colors should change. I have attempted this but with no ...

"Enhance your HTML table by selecting and copying cell values with a simple click and CTRL +

I stumbled upon a fantastic script for highlighting HTML table rows and it's working perfectly: I decided to modify the onclick event to onmouseover and included additional code to select a cell by clicking on it. Now I can select, check which one is ...

developing a shader that transitions between day and night based on the movement of a light source

I've set up a scene with a sphere illuminated by a DirectionalLight to simulate the sun shining on Earth. My goal is to incorporate a shader that displays the earth at night on the unlit portions of the globe and during the day on the lit areas. Event ...

Hide modal once form has been successfully submitted

Is it best practice to pass handleClose into ForgotPasswordFormComponent in order to close the modal after form submission, or is there a better way to achieve this? <StyledModal open={openModal} onClose={handleClose} closeAfterTransition slots={{ bac ...

Conceal the element at all times

I'm facing a challenge with a paragraph element that is dynamically filled with content using Javascript. I need to hide the element whenever it doesn't have any text within it. However, I want to avoid using setTimeout or setInterval for this ta ...

Creating a transparent background in a three.js canvas: a step-by-step guide

I came across a wave particle animation on Codepen (https://codepen.io/kevinsturf/pen/ExLdPZ) that I want to use, but it has a white background. However, when I try to set the body background to red, it doesn't show up once the canvas is rendered. I ...

Converting MySQL data to JSON format in PHP, including handling nested objects

Hey there, I'm currently working on organizing these results into arrays in PHP so that I can convert them into JSON objects and send them over to the client. Here is what the query results look like: id name hours cat status 3bf JFK Int 24 ...

Utilizing requirejs or grunt for concatenation and minification greatly enhances the performance of AngularJS implementations

I'm facing a dilemma with my Angular app. I have several JS files included in the index.html file, and when the app loads, all these files are downloaded before the app is ready. <html> ... <script src="scripts/controllers/loginController.js ...

Organize database entries by categories for easy navigation

I've developed a web application centered around TV Shows to enhance my understanding of AngularJS. Within my database, I have a table containing various TV shows, each with an assigned category column. For instance, "Dexter" is categorized as "thrill ...

What is the most effective way to showcase a list of image URLs in HTML with Vue?

Currently, I am working with an array called thumbnails that holds the paths to various images. My goal is to use masonry in Vue to arrange these images in a grid format, but I'm encountering some difficulties achieving the desired outcome. This is m ...

What is the best way to ensure that the checkbox is not affected when you click on the area?

If the user interacts with the checkbox, I don't want the handleClick function to execute. Is there a way to exclude it or prevent the click event from triggering? <div ... onClick={this.handleClick}> <div> some content here < ...

How to show ngFor value from Angular in a separate tag

I have a list of companies that I want to display in the following format: <div class="col-md-4"> <select ngModel="selectedCompany" style="width:400px;"> <option *ngFor="let x of mycompanylist&q ...

Finding the Determinant of a 4x4 Matrix: A Ray-Tracing Adventure in JavaScript

Currently, I am in the process of developing a raytracer using Javascript/Canvas and following "The Ray Tracer Challenge" by Jamis Buck. Initially, my code successfully computed the determinant of a 3x3 matrix but encountered issues with a 4x4 matrix. As a ...

Angular - Error: Cannot read property 'publishLast' of undefined

My goal is to prevent multiple requests from being created when using the async pipe. I am facing an issue with a request to fetch a user from the API: getUser() { this._user = this.http.get<User>(environment.baseAPIUrl + 'user') ...

Can the order of React lifecycle events be reliably predicted across different components?

Is there a clear documentation on the guarantees of React lifecycle order across separate components? For instance, if I have: <div>{ x ? <A /> : <B /> }</div> When x changes from true to false, one component will unmount and the ...

Exploring the differences between UTC and non-UTC date formats in Javascript

When working with JavaScript, I encountered a challenge in comparing two dates that are formatted differently. Specifically: 2015-09-30T00:00:00 and 9/30/2015 12:00:00 AM The former is in UTC format while the latter is not. Despite referring to the same ...