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!