Here you need a comprehensive solution. As @sercxjo correctly noted, the processing of leaving the site is not a panacea.
When the page has loaded, we start the timer, which at certain intervals Ajax sends to the server the presence information. The server, in turn, receives the request and records the time of the last access. Further, to find out if the user is present or not, it is enough for the server to calculate the interval between the time of the last call by timer and the current moment. If this interval exceeds the interval of the client timer, then Ajax requests from the browser no longer arrive and the user is gone.
The more often the browser will send such requests, the more accurate the server will know about who is present and who is not. But, at the same time, frequent calls increase the load on the server. Therefore, the optimal polling interval should be calculated on the basis of the estimated number of online users, the computing power of the server and common sense. For example, why pull a server every 5 seconds if 2-5 minutes is not critical. Calculation type: 100 онлайн-пользователей / интервал в 5 сек. = дают среднюю нагрузку 20 запросов в секунду
100 онлайн-пользователей / интервал в 5 сек. = дают среднюю нагрузку 20 запросов в секунду
.
Plus, the processing of leaving the page, you can hang up sending Ajax-request with the information that the user has left. If this event works, then the server will know the exact moment of departure.
With a large number of visits with information about the presence is worth thinking about how to store this information on the server. To prevent each request from pulling the server screws each time, you can use memcached or a MySQL table with HEAP type. The peculiarity of HEAP-tables is that they keep their contents in the operative and do not write it on a screw, and this is quite enough for information on the presence of it.
Something like this...
UPD: If you develop the idea further, then you can work out the system with automatic load balancing on the server. For example, in a server script we sew a constant: process no more than 20 requests per second. Then, in response to the Ajax request from the client, you can send him the recommended interval for the next call from him. The server knows the current number of online clients (for example, 300 pcs.), The server knows the constant of 20 requests per second. At the time of the next request from the client, a simple calculation of 300 шт. / 20 = 15 сек.
300 шт. / 20 = 15 сек.
and these 15 sec. sent to the customer. And the client, having received the answer, writes this recommended interval into his timer until the next call.
Thus, at peak times, the server itself will regulate the number of requests sent with the presence information.