简体   繁体   中英

Pages load very slow due to notification polling

I am working on notification system, but my pages load very slow due to polling of notification. I mean very slow, but when I comment out notification code then it runs smoothly. Here is my ajax code for polling notifications :

function pollNotification() {

$.ajax({
    method: 'POST',
    url: urlGetNotification,
    async: true,           
    timeout: 0,         
    cache: false,
    data: {
        _token: token
    },

}).done(function (notifs) {
    //my code here

}).always(pollNotification);
}

Here is my server side php(laravel framework) code for fetching notifications :

public function getNotification()
{
    $count=0;
    $user = User::select('last_notif_timestamp')->where('id',Auth::user()->id)->get(); // fetching last timestamp when user clicked on notification

    $notification = Notification::where('receiver',Auth::user()->id)->orderBy('updated_at','desc')->get(); //checking for notification in table
    $prevDate = Session::get('prevDate'); //temporary variable to check when the last notification came

      if($notification->count()>0) {
          if ($prevDate == null || $prevDate < $notification[0]->updated_at) {
              Session::set('prevDate', $notification[0]->updated_at);

              $notifications = array();
              foreach ($notification as $notif){
                  if($notif->updated_at > $user[0]->last_notif_timestamp) //Keeping track of notification counter
                      $count++;
                  $notifications[] = $notif;
              }

              return response()->json(['notifications'=>$notifications, 'count'=>$count],200);
          }
          else{
              sleep(10); // Sleeping for 10 seconds for next poll
              self::getNotification(); //calling function recursively
          }
      }
    sleep(10);
    self::getNotification();
}

In short this code checks for notification and if new notification are present then it returns those notifications with count value. If there are no notification then it sleeps for 10 seconds and calls the same function recursively.

Please suggest any solution to load the pages faster. Thanks!

Why do you want to wait on php side?

Currently you force your php script to wait before sending a response to you ajax request and this wait can be very long and memory consuming for the server with the recursive calls.

You can do a simple polling on the Javascript side using setTimeout(), for example. On the php side, you can just return the notification array even if it is empty (check it using Javascript) without any sleep(). This should at least reduce the response time of your ajax request and maybe the loading time of pages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM