Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize $interval for real time notifications in Angularjs?

I am working on a social networking site. I have used following code to show the total notifications count in real time for a user.

Code:

    function load_notifications(){
        $http.get('http://localhost:3000/load').success(function(data){
            $scope.totalNotify = data.total;
        });
    };
load_pictures();
$interval(function(){
        load_notifications();
    },300);

basically, this code checks the DB continuously at a given interval and if there is some change, it update the $scope value. But when I tried to check it with two different user in different browsers, it chokes the browser because of polling requests.

Is there any way to improve this method or have any other better alternative? I am building my application using PHP and AngularJS. But I am open to other options for this module too.

like image 998
Farjad Hasan Avatar asked Mar 24 '26 04:03

Farjad Hasan


1 Answers

This should be done using web sockets, not a polling ajax request.

JS: AngularJS and WebSockets beyond

PHP: How to create websockets server in PHP

Specifically, for web sockets using PHP, I would use Rachet.

A starting point for the PHP would be here: http://socketo.me/docs/hello-world

This hello world tutorial shows you basic javascript and PHP for interacting through Rachet.

like image 81
Mikel Bitson Avatar answered Mar 25 '26 18:03

Mikel Bitson