Let’s take this a step at a time.
When the page loads, you want the timer to start. When it triggers you want to update Content
$(function() {
startRefresh();
});
function startRefresh() {
setTimeout(function () {
$.get('test.php', function(data) {
$('#content').html(data);
});
}, 30000);
}
The next part is the challenging one, for when the timeout triggers you want to set up another timer. You don’t want to have both the timer setup and the page updating occurring at the same time, for then you have the same troubles that you currently have. We can’t do that easily at this stage, but as Martin Fowler and Kent Beck said:
When you find you have to add a feature to a program, and the program’s code is not structured in a convenient way to add the feature, first refactor the program to make it easy to add the feature, then add the feature.
Let’s refactor the code so that it’s all encapsulated in the anonymous function, and extract out the different behaviours to separate functions. After we’ve done that we can then add in the feature to trigger another timer.
$(function () {
function updateContent() {
$.get('test.php', function (data) {
$('#content').html(data);
});
}
function startRefresh() {
setTimeout(updateContent, 30000);
}
startRefresh();
});
From within the new updateContent we’re wanting to set a new timer, so startRefresh is now the wrong function name. We can rename that function to resetTimer and add some code to assign the timer to a variable, so that we can then reset things based on that.
$(function () {
var timer,
updateContent;
function resetTimer() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(updateContent, 30000);
}
updateContent = function updateContent() {
resetTimer();
$.get('test.php', function (data) {
$('#content').html(data);
});
}
resetTimer();
});
Because the updateContent function calls the resetTimer one, it really should be defined after it. By declaring updateContent as an inline expression we can help to ensure that the function isn’t declared out of turn.
Now the code is ready to let us reset the timer from within the updateContent function, and we can also reset it when activity occurs too.
$(function () {
var timer,
updateContent;
function resetTimer() {
if (timer) {
window.clearTimeout(timer);
}
timer = window.setTimeout(updateContent, 30000);
}
updateContent = function () {
resetTimer();
$.get('test.php', function (data) {
$('#content').html(data);
});
};
resetTimer();
$(document.body).on('mousemove keydown', resetTimer);
});