Page refresh when there is no activity

I am using the following function to refresh a page every 30 seconds.


$(function() {
    startRefresh();
});

function startRefresh() {
    setTimeout(startRefresh,30000);
    $.get('modules/berichten.php', function(data) {
        $('#content').html(data);
    });
}

What I need to include though is that this function only will run when there is no user activity (keystoke or mouse move). What should I add to this function to make that happen

Quite simple. When the user presses a key or moves the mouse, restart the timeout, like so:


(function() {
    var timeout;
    
    $(function() {
        startRefresh();
    });

    function startRefresh() {
        clearTimeout(timeout); // stop previous timeout
        timeout = setTimeout(startRefresh, 30000);
        $.get('modules/berichten.php', function(data) {
            $('#content').html(data);    
        });
    }

    $(body).on('mousemove keydown', function() {
        startRefresh(); // restart timeout
    });
}());

I’ve wrapped the whole thing in a self executing anonymous function to make sure this stuff is contained and doesn’t “bleed” into the global scope.
See http://markdalgleish.com/2011/03/self-executing-anonymous-functions/

#protip: when testing this stuff, change the timeout to something like 3 seconds, so you don’t have to wait for ages for something to happen. Or as the case may be, not to happen :wink:

Hi ScallioXTX. That works great. Thank you so much. I have one last question about this. Is it somehow possible to integrate some kind of loading image or text in this function that shows when the page is loading? Thank you in advance.

Edit: I think I found a way:


(function() {
    var timeout;
	var loader = jQuery('<div id="loader"><img src="images/loading.gif" alt="loading..." /></div>')
	.hide(); 
	
    $(function() {
		loader.show();
        startRefresh();
    });
 
    function startRefresh() {
        clearTimeout(timeout); // stop previous timeout
        timeout = setTimeout(startRefresh, 30000);
        $.get('modules/berichten.php', function(data) {
            $('#content').html(data);    
        });
    }
 
    $(body).on('mousemove keydown', function() {
		loader.hide();
        startRefresh(); // restart timeout
    });
}());

I only think I haven’t included it in a proper way because the loading image and text are showing all the time, where I actually want it to hide when there is activity (mousemove keydown). What should I adjust in the above to make this happen.

Do a loader.show() in your startRefresh function, and then loader.hide() in the callback function of $.get in that function