要回答這個問題,我會承擔下列:
- 在您需要異步運行後臺作業
的能力後端 的前端
- 一個JavaScript計時器就足夠了倒計時(不管後臺工作是否稍微休息)
基本的想法是,你發送一個日期戳到服務器,在前端開始倒計時,並且任何時候有一個互動再次嘗試活動,你問問rver(相同的後臺任務),如果時間間隔已經完成。
下面的解決方案是開始,並不是管理這種交互所需要的完整版本。
在前端你能想象做這樣的事情:
function restoreAndStartTimer(response, initialLoad){
var secondsToCountDown = 10;
//Here we can use the server response to tell us if there's already
//a timer running
if(response.timerRunning){
secondsToCountDown = response.secondsRemaining;
}
//Now kickoff the front-end timer
function countdown(){
//Add code here to display stuff to the screen, etc
if(secondsToCountDown !== 0){
secondsToCountDown--;
setTimeout(countdown, 1000);
}
};
if(initialLoad){
if(response.timerRunning) countdown();
} else {
countdown();
}
};
//Click handler, assuming you use jQuery
$('#myActivityButton').on('click', function(){
$.ajax({
url: 'https://...',
type: 'POST',
//Grabs the time of the click and sends it off to the server
data: { currentTime: new Date() },
success: function(response){
restoreAndStartTimer(response, false);
}
});
});
$(function(){
//On document ready
//This should be wrapped as a function to avoid repetition, but for the sake of
//expediency using this editor...
$.ajax({
url: 'https://...',
type: 'POST',
data: { currentTime: new Date() },
//If a user had reloaded the page while a timer was running, it will get picked
//up here, otherwise it does nothing.
success: function(response){
restoreAndStartTimer(response, true);
}
});
});
至於後端,你會運行一個後臺線程的一些方法。該線程將通過前端發送的初始時間戳獲取時間和返回任何根據狀態以下響應:
response.timerRunning = true
和response.secondsRemaining = #ofSeconds
考慮到時間間隔尚未完成
response.timerRunning = false
當時間間隔終於完成時
充其量,您可以嘗試'window.onbeforeunload'來以某種方式通知服務器,您的瀏覽器窗口正在關閉。 –