我正在嘗試爲Web應用程序編寫一個簡單的JavaScript頁面計時器。計時器將記錄按下按鈕(隨着用戶進入頁面)的時間並在按下按鈕(當用戶離開頁面時)再次記錄時間。兩次的差值將給出時間用戶在頁面上度過的時間。如果他們在頁面上停留了2秒以上,秒數將被記錄到手持本地數據庫中。如果警報已被註釋掉,此JavaScript代碼將無法正確執行。
我遇到的問題是,如果starttime函數中的警報被註釋掉,下面的代碼將不起作用。
$(document).ready(function() {
$('div.m1-root').click(function() {
//simulate the pagetransition events in mobile framework
pagename= $(this).attr('id');
starttime();
//alert("You are leaving\n" + pagename + "\n you were here for \n" + time.toFixed(0) + " seconds"); // This alert will fire but only record the proper time if the next alert is fired
});
});
function starttime()
{
//create a starting timestamp, number of milliseconds since midnight Jan 1, 1970
start = new Date().getTime();
//alert(+ start); // if this alert is commented out the time is not started
pagetime();
}
function pagetime(pagename){
time = (new Date().getTime() - start)/1000;
//alert("you have been on " + pagename + " for \n" + time.toFixed(0) + " seconds");
//before we transition, log previous page and time
//if time is greater than 3 seconds we log it (I changed it to -1 so that I would see any figure while testing)
if (time >-1)
{
//DataBase update
db.transaction(function(tx) {tx.executeSql('INSERT INTO CBNapp_Usage VALUES (time)',function(tx,result) {},function(tx,Error) {});});
//alert("You spent " + time.toFixed(0) + " seconds on " + pagename);
}
}
我已經看過SO和網絡上所遇到類似的情況,但我似乎無法得到任何的這些想法在這裏工作。我明白這可能是一個計時問題,並嘗試setTimeout或返回true來延遲的事情,但它不起作用。
有人可以看看代碼,並建議我如何才能使它正常工作?
這是我第一次從頭開始JS。請提供具體的例子,以便我可以跟隨他們。該數據庫也沒有記錄,但我會在稍後處理。如果您有任何其他具體的建議如何改善這一點,我會歡迎他們。
感謝您抽出時間幫助。
特德
我對你的示例有點困惑。兩次點擊按鈕都會運行相同的代碼...因此,您只需要覆蓋開始的值,然後立即*記錄結束時間,因此最好是幾毫秒。 – bhamlin 2012-03-01 01:33:25
感謝您的回覆。當他們進入我正在嘗試保存的變量時,我開始了。當他們離開頁面並計算差異以獲得用戶在頁面上的時間時,我又一次得到了時間。當警報未被評論時,它運作良好。我應該如何做不同? – user1224675 2012-03-01 02:07:29