I am trying to write a simple JavaScript page timer for a web app. The timer will record the time at the press of a button (as the user enters the page) and record the time again at the press of a button (when the user leaves the page) The difference of the 2 times will give the time the user spent on the page. If they stayed on the page for more than 2 seconds the number of seconds will be recorded to the local database on the hand held.
The problem I am having is that the following code will not work if the alert in the starttime function is commented out.
$(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);
}
}
I have looked on SO and the web and have come across similar situations but I can not seem to get any of those ideas to work here. I understand that this may be a timing problem and have tried a setTimeout or return true to delay things but it does not work.
Could someone please take a look at the code and suggest how I might be able to get it to work properly?
This is my first from scratch JS. Please provide specific examples so I can follow them. The database is also not recording but I will work on that later. If you have any other specific suggestions as to how to improve this I would welcome them.
Thanks for taking the time to help.
Ted
It looks like you’ve got all your code inside the button click handler. It only appears to be working when you have the alert, because the alert creates the appearance of delay.
You need to put starttime() outside of the click handler, and it shouldn’t be calling pagetime().