2016-09-25 80 views
0

請幫幫我。我必須找到用戶在頁面上完成活動的總時間。我做了jquery代碼,這段代碼發現如果用戶閒置10秒,代碼增加其空閒時間。但是這個代碼的問題是,當用戶在該頁面上連續閒置(例如30秒)時,代碼必須在空閒時間內總共增加10秒+10秒+10秒總共30秒。它在閒置時間只增加10秒,跳過20秒的休息時間,就像我上面提到的那樣。儘管用戶在超時後在頁面上完成了像mousemove等一些活動,但仍然可以在空閒時間內再次增加10秒,但這次只能再增加10秒,而不是全時間範圍。jquery timeout函數在一次調用後沒有被再次調用

問題可能會超時。超時功能在一次調用後不會被再次調用。我想不會有連續的超時通話。我不確定。

這裏是代碼

var timeoutID; \t 
 
var start, end, pagefocustime = 0; 
 
var opentime, midtime = 0; 
 
var exacttime = 0; 
 
var inactivetime = 10000, idletime = 0; \t 
 
var window_focus = true; 
 
$(document).ready(function() { 
 
    start = performance.now(); //Calculating Startup Time 
 
    midtime = start; 
 
    
 
    $(window).on('blur', function() { 
 
\t window_focus = false; 
 
    end = performance.now(); 
 
    pagefocustime += end - midtime; 
 
\t exacttime += end - midtime; 
 
    }) 
 

 
    $(window).on('focus', function() { 
 
\t window_focus = true; 
 
    midtime = performance.now(); 
 
    }) 
 
    
 
    if(window_focus){ 
 
\t function setup() { 
 
\t \t this.addEventListener("mousemove", resetTimer, false); 
 
\t \t this.addEventListener("mousedown", resetTimer, false); 
 
\t \t this.addEventListener("keypress", resetTimer, false); 
 
\t \t this.addEventListener("DOMMouseScroll", resetTimer, false); 
 
\t \t this.addEventListener("mousewheel", resetTimer, false); 
 
\t \t this.addEventListener("touchmove", resetTimer, false); 
 
\t \t this.addEventListener("MSPointerMove", resetTimer, false); 
 
\t \t startTimer(); 
 
\t } 
 
\t 
 
\t setup(); 
 
\t 
 
\t function startTimer() { 
 
\t \t // wait 10 seconds before calling goInactive 
 
\t \t timeoutID = window.setTimeout(goInactive, 10000); 
 
\t } 
 
\t 
 
\t function resetTimer(e) { 
 
\t \t window.clearTimeout(timeoutID); 
 
\t 
 
\t \t goActive(); 
 
\t } 
 
\t 
 
\t function goInactive() { 
 
\t \t idletime = idletime + inactivetime; 
 
\t \t console.log("I am called"); 
 
\t } 
 
\t 
 
\t function goActive() {  
 
\t \t startTimer(); 
 
\t } 
 

 
    } \t 
 
    $(window).on('beforeunload',function(){ 
 
    end = performance.now(); 
 
    pagefocustime += end - midtime; 
 
    console.log("Total page focus Time : " + pagefocustime); 
 
\t opentime = end - start; 
 
\t console.log("Total Page Open time : " + opentime); 
 
\t exacttime = pagefocustime - idletime; 
 
\t console.log("exact time : " + exacttime); 
 
    });    
 
});

請幫助。 非常感謝提前

+0

如果你正在使用jQuery,爲什麼不用'$(this).on(「mousemove mousedown keypress etc」,resetTimer)'而不是對'addEventListener()'進行七次單獨調用? – nnnnnn

回答

0

您可以調用'goInactive'方法中的'startTimer'來再次開始檢查。

當您在該代碼中時,可以將所有這些事件名稱放入一個數組中,然後使用map函數來附加偵聽器。