Reputation: 135
I am working on a chat system that should trigger an AJAX request whenever the user is inactive for a certain amount of time. I tried to solve it in JavaScript only, but always failed when trying to set back the inactive clock whenever user gets active. Is there any way to achieve this functionality?
As a possible option I identified HTML5 Web Workers. But a created worker cannot access the DOM what I need to do for processing the response of the AJAX request. To bypass this, the worker can post some kind of messages to the main thread, but there I lost the overview completely.
At the moment, I have three relevant code elements that should be able to interact with each other.
Start inactive clock (starts when user is inactive, should trigger AJAX request after some time, but should be able to be stopped by stop inactive clock function):
function startInactiveClock() {
var waitingTime;
var waitStart = performance.now();
// waiting time limit set to 30 seconds
while (waitingTime < 30000) {
// unfortunately kills the web browser
waitingTime = performance.now - waitBegin;
}
triggerAJAXRequest();
}
Trigger AJAX request (should be able to access DOM):
function triggerAJAXRequest() {
$.ajax({
...
success: function(data, status, xhttp) {
response = data;
var newChatMessage = '<div class="ChatMessage">' + response + '</div>';
$("#chatHistory").prepend(newChatMessage);
},
...
});
$("#userInputTxt").focus();
}
Stop inactive clock (starts when user is active, should be able to stop the start inactive clock function):
function stopInactiveClock() {
// do something to stop the inactive function counter
}
Upvotes: 1
Views: 249
Reputation: 534
You should instead use window.setTimeout.
So you could start the timeout when the inactive period is met and then check again within the timeout so that you are sure the user has been inactive and then trigger the ajax function.
Upvotes: 1