我正在尝试为 Web 应用程序编写一个简单的 JavaScript 页面计时器。计时器将在按下按钮时记录时间(当用户进入页面时)并在按下按钮时再次记录时间(当用户离开页面时) 2 次的差将给出时间用户在页面上花费。如果他们在页面上停留超过 2 秒,秒数将被记录到手持设备上的本地数据库中。
我遇到的问题是,如果 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 和 web 并遇到过类似的情况,但我似乎无法让任何这些想法在这里发挥作用。我知道这可能是一个时间问题,并尝试了 setTimeout 或返回 true 来延迟事情,但它不起作用。
有人可以看看代码并建议我如何让它正常工作吗?
这是我的第一个从零开始的 JS。请提供具体示例,以便我可以遵循它们。数据库也没有记录,但我稍后会处理。如果您对如何改进这一点有任何其他具体建议,我会欢迎他们。
感谢您花时间提供帮助。
泰德