Polling AJAX client for P2P file sharing website I have this function:

function Filer() {
    setTimeout(function () {
        $.ajax({
            url: '/Pages/Handlers/filecheckerhandler.ashx',
            data: { id: GetMyId(), sid: GetSessionId() },
            success: function (data) {
                if (data == "true") {
                    window.open('/Pages/Handlers/livesharehandler.ashx?id=' + GetMyId() + '&amp;sid=' + GetSessionId(), '_self');
                }
            },
            global: false
        });
        Filer();
    }, 2000)
}
Filer();


Basically, my website allows for peer to peer file sharing online. What this does is checks for files and if it is present the file will be downloaded and the file will be deleted from the server.

The function is recursive as you can see. This is making a lot of requests.

But my function is making a lot of requests which is making the site slow. What can be done?
You are polling filecheckerhandler.ashx regularly at two-second intervals. The fact that such polling is implemented using recursion, with Filer() calling itself, is irrelevant to your performance problem.  You could improve the client code by using setInterval() instead of setTimeout(), but the overall system performance will be just as bad.

There are only three strategies to improve system performance:


Lengthen the polling interval.  Especially if no activity has occurred recently, activity is less likely in the near future, so the polling interval could be adaptive.
Improve the efficiency of filecheckerhandler.ashx.  The constraining factor is probably load on the server, rather than load on the client, so any efficiency gains on the server would likely make an impact.
Improve the efficiency of the communication protocol.  Each AJAX request is essentially a new HTTP request, with the only optimization being possible HTTP keep-alive, which might avoid the TCP handshake.  Consider a technique that is more suitable for client-to-server notifications, such as Comet.