Is there a way to monitor real-time updates without relying on setInterval or timeout functions?

Currently in the process of building a social network, I am working on fetching live notifications. The current approach involves sending an AJAX request every few seconds using setInterval. The code snippet for this operation is as follows:

setInterval ( function(){
    url = base_dir+"/ajax/file.php";
    data = "data=someData";
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: "json",
        beforeSend: function(x) {
            if(x && x.overrideMimeType) {
                x.overrideMimeType("application/json;charset=UTF-8");
            }
        },
        success: function(JSON){
            // retrieve data here   
        }
    });
}, 5000);

Although this method works effectively, my concern lies with the potential server overload it may cause. Experimenting with the comet technique didn't yield desired results either, as it seemed to generate more requests compared to the previous approach. Are there alternative techniques available for efficiently pushing this live data?

EDIT: In order to implement long polling, I followed the example provided at :

(function poll(){
    url = base_dir+"/ajax/file.php";
    data = "data=someData";
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: "json",
        beforeSend: function(x) {
            if(x && x.overrideMimeType) {
                x.overrideMimeType("application/json;charset=UTF-8");
            }
        },
        success: function(JSON){
            // retrieve data here   
        },
complete: poll,
timeout: 5000
    });
})();

It's possible that there might be some misunderstanding on my part regarding the comet principle.

PHP code:

// Checks for new notifications, and updates the title and notifications bar if there are any
 private static function NotificationsCounter (){
    //self::$it_user_id                                     = query that retrieves my id for further checks;                                                        
    //$friend_requests_count                                = query that retrieves the friend requests count;
    //$updates_count                                        = query that retrieves the updates count;               
    $total_notifications                                    = $friend_requests_count+$updates_count;

    if ($total_notifications > 0) $addToTitle = "(".$total_notifications.")";
    else $addToTitle = "";

    if ($updates_count > 0) $counterHTML = "<span class='notification_counter' id='updates_counter' style='float: right;'>".$updates_count."</span>";
    else $counterHTML = "";

    $data = array("counter"=>$total_notifications,"addToTitle"=>$addToTitle,"counterHTML"=>$counterHTML,);
    echo json_encode($data); // parse to json and print
}

In light of Facebook also utilizing PHP, how do they manage this process?

Answer №1

Utilizing websockets is the recommended approach. By connecting to the server and registering an onmessage handler, you can efficiently receive any data sent by the server without the need for a timeout.

Prior to implementation, it's crucial to verify websocket support in your specific browser. Currently, only Chrome, Opera, and Safari offer compatibility.

if ('WebSocket' in window){
   /* Proceed with WebSocket code as it is supported */
} else {
   /* If WebSockets are not supported, consider using alternatives like long-polling */
}

Establishing Connection:

var connection = new WebSocket('ws://example.org:12345/myapp');

Event Handlers:

connection.onopen = function(){
   console.log('Connection open!');
}

connection.onclose = function(){
   console.log('Connection closed');
}

connection.onmessage = function(e){
   var server_message = e.data;
   console.log(server_message);
}

For further reference, check out the documentation at:

Answer №2

It is anticipated that websockets will become the preferred method of communication once they are widely supported across all major browsers, which may take at least five years.

Currently, Facebook chat relies on comet technology and a significant number of servers to function. For a more efficient solution, there are two possible alternatives to consider.

  1. Adjust the polling interval. By optimizing this for user experience, it's possible to have longer intervals without compromising performance. Conducting user testing will help determine the ideal interval, but frequent polling every 5 seconds may be unnecessary. This approach also offers scalability by simply increasing the interval during peak usage periods.

  2. Implement HTTP validation caching. To reduce the weight of requests, the server can respond with data only when there have been changes since the last request. Developing a custom system using ETag or Last-Modified headers for modification tracking on the server can save bandwidth and improve efficiency.

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

Sending emails with SMTP in JavaScript using the mailto form

I'm facing a challenge with my form. I am looking for a way to have the Send-email button trigger mailto without opening an email client, instead automatically sending via JavaScript (smtp). I'm not sure if this is achievable or if I'm askin ...

Track the number of times a button is clicked to generate a prominent "Main Event" section

Currently, I am working on a Tourism website that showcases numerous tours. Utilizing WordPress, I have established a custom post type titled Tours. Each tour is equipped with a Book Now button, which has been generated as a custom meta box. This button d ...

Tips for making an appended element match the height of an image

After embedding the div .soonOverlay into specific .smallCatalogBlock's, I am facing difficulty in adjusting the height of soonOverlay to match only the height of the img within smallCatalogBlock. Currently, its height extends throughout the entire co ...

Routing with nested modules in Angular 2 can be achieved by using the same

Encountering a common issue within a backend application. Various resources can be accessed through the following routes: reports/view/:id campains/view/:id suts/view/:id certifications/view/:id Note that all routes end with the same part: /view/:id. ...

Modifying the content of JSON key values

In my application, I am using MongoDB, Express, and MongoDB. When receiving data on the server side, it comes in the form of an array of objects (JSON) named upProbations. For example, let's say I find information about Max: [ { Name ...

jQuery's z-index feature is malfunctioning

When I hover over my menu, a box fades in. However, there is a small icon behind this box that I want to move to the front so it can be visible during hover. To see an example of my menu, click here: Navigation I attempted to address this by using jQuer ...

Verify whether the document includes a class that closely matches the provided string using Javascript

I need help identifying elements that include the letters 'ad'. For example: <iframe class="container" /> <!-- Not relevant --> <a class="adp" /> <!-- Relevant --> <a class="adleft" /> ...

Tips on Calculating the Number of Object Properties and Presenting Each Value Individually on a Dynamic Button with Click Event Attached

When it comes to displaying dynamic data with markers on a map, everything works fine up until this point. However, I've encountered some issues that I'm currently stuck on and not sure how to proceed. Dynamic data: { "page": 2, "data" ...

React Native Header Icon Not Showing on the Left Side

I'm brand new to react and currently working on a project where navigation is done through a hamburger menu. I haven't encountered any errors in my code, but for some reason, the hamburger menu icon isn't displaying as expected. Interestingl ...

Tips for accessing the current state/value in a third-party event handler?

Consider the following scenario: function MapControl() { const [countries, setCountries] = useContext(CountriesContext) useEffect( () => { ThirdPartyApi.OnSelectCountry((country) => { setCountries([...countries, country]) }) }) ...

Is there a reason for the absence of the Revit category attribute in the JSON response retrieved from the GET request :urn/metadata/:guid/

After receiving the information from the endpoint regarding Revit Models uploaded to my bucket, I noticed that the JSON response contains multiple objects. These objects seem to represent Revit elements, each with all parameters except for the Revit Categ ...

How to modify the content type in an Angular.js $http.delete request

When making a $http.delete request in my Angular app, I include a config object using the following approach: return $http.delete('projects/' + projectID + '/activityTypes', {data: [{id: 2}]}) This method attaches the values from my d ...

Despite the presence of a producer and topic, sending Kafka messages is proving to be a challenge

Currently, I am using TypeScript and the KafkaJS library on my local machine with a single Kafka broker. After successfully connecting a producer, confirming the creation of my topic, and creating messages like so: const changeMessage = { key: id, ...

Utilize string paths for images instead of requires when resolving img src and background-image URLs

I have successfully implemented image loading with webpack using the file loader, but only when I require or import images. I am curious about how create-react-app achieves the functionality where everything in the public folder is accessible, for example, ...

Learn how to deactivate the pause button with just one click and re-enable it once the popup appears using Angular2 and Typescript

Can anyone assist with solving an issue I am facing with a timer and a pause button? I need the pause button to be disabled once clicked, until a popup appears, then it should become enabled again. My code snippet is provided below: HTML: <button md-i ...

Guide to utilizing jquery within node.js

Can anyone assist me with using jQuery in Node.js? I have the following code: const jsdom = require("jsdom"); const { JSDOM } = jsdom; const { window } = new JSDOM('<!DOCTYPE html>'); const $ = require('jquery')(window); var con ...

Issue with HTML5 Video Play on Hover Functionality Ceases to Work Upon Loading Dynamic Content

I recently implemented a feature on my WordPress site that allows videos to start playing when the mouse hovers over their thumbnails and pause when it leaves. However, I encountered an issue where this function works perfectly upon initial page load but f ...

Preload-webpack-plugin does not support pre-fetching files

I have a query about prefetching and preloading content. In my vue app, I noticed that after building, I have duplicate files loaded in my dist/index.html file. Here is an example: Additionally, the "scripts" are not being preloaded/prefetched as expec ...

Do I have to include reject() in the executor when using promises in express.js?

If we choose not to handle rejection, is it necessary to include the reject parameter in the promise executor? For example: new Promise((res) => { res(a); }) ...

What is the best way to retrieve the current value of a React useState hook within a setInterval function while using Highcharts

import Error from 'next/error' import React, { useState, useEffect } from 'react' import Highcharts from 'highcharts' import HighchartsReact from 'highcharts-react-official' function generateChart() { const [co ...