Search code examples
javascriptjqueryajaxsettimeoutpolling

How can I make this setTimeout call first thing on page load THEN wait five seconds?


I have this method:

$(document).ready(function(){ 

    var rootPath = getRootPartofPathName();
    (function poll() {
        setTimeout(function () {
            $.ajax({
                type: 'GET',
                url: rootPath + '/data/notifications?method=getNotificationSizes',
                success: function (data) {
                    handleNotifications(data); 
                },
                complete: poll
            });
        }, 5000);
    })();
}); 

But it only calls 5 seconds after the page has loaded. How can I make it start polling on first page load?


Solution

  • Create the timeout in the callback, and there's no need for the self-executing function either, then simply call poll() on page load:

    function poll() {
        $.ajax({
            type: 'GET',
            url: rootPath + '/data/notifications?method=getNotificationSizes',
            success: function (data) {
                handleNotifications(data); 
                setTimeout(poll, 5000);
            },
            complete: function() {
    
            }
        });
    }
    
    poll();