Web アプリ用の単純な JavaScript ページ タイマーを作成しようとしています。タイマーは、ボタンを押したとき (ユーザーがページに入ったとき) の時間を記録し、ボタンを押したとき (ユーザーがページを離れたとき) に再び時間を記録します。ページで費やしたユーザー。ページに 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 です。私が従うことができるように、具体的な例を提供してください。データベースも記録されていませんが、後で作業します。これを改善する方法について他に具体的な提案があれば、私はそれらを歓迎します.
お時間を割いていただきありがとうございます。
テッド