I have used this piece of code for a timer. But I am not able to set up a logic to get the total seconds elapsed on this page before pressing a refresh button or redirecting to another page. I also want to pass the value of total seconds elapsed to my database.
Timer Code:
<html>
<head>
<Script Language="JavaScript">
var startDate = new Date();
var startTime = startDate.getTime();
function seconds_elapsed ()
{
var date_now = new Date ();
var time_now = date_now.getTime ();
var time_diff = time_now - startTime;
var seconds_elapsed = Math.floor ( time_diff / 1000 );
document.display.timeElapsed.value = pad ( seconds_elapsed );
setTimeout( "seconds_elapsed ()", 1000 );
return ( seconds_elapsed );
}
function pad ( num )
{
return ( ( num > 9 ) ? num : "0" + num );
}
</Script>
</head>
<body onLoad="seconds_elapsed()">
<form method="get" name="display" action="timer.php">
<input name="timeElapsed" type="text" size=8>
</form>
</body>
</html>
Here a small example made with window.performance.now()
<body onload="startTimer()">
<button onclick="showElapsedTime()">Show Seconds</button>
</body>
<script>
var start;
var end;
function startTimer() {
start = window.performance.now();
console.log(start);
}
function showElapsedTime() {
end = window.performance.now();
var seconds = (end - start) / 1000;
alert("Time elapsed: " + seconds.toFixed(2) + " seconds");
}
</script>
You can do like that :
Second in the page:
<html>
<head>
<Script Language="JavaScript">
var startTime, endTime;
function start() {
startTime = new Date();
};
function end() {
endTime = new Date();
var timeDiff = endTime - startTime; //in ms
// strip the ms
timeDiff /= 1000;
// get seconds
var seconds = Math.round(timeDiff);
window.location="https://website.com/storetimer.php?second="+seconds;
}
</Script>
</head>
<body onLoad="start()">
<button onclick="end()">Click me</button>
</body>
Now in new page store with insert in your db the variable second like:
$second=$_GET['second'];
//insert code
Send an AJAX ping every second, or every time you want.
Or use onunload / onbeforeunload function and send an ajax when leaving. https://stackoverflow.com/questions/4945932/window-onbeforeunload-ajax-request-in-chrome
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.