I'm trying to write a script where I need a timer to cou开发者_高级运维nt the number of seconds a popup is open. I'm new to programming but I assume you use javascript for it?
Within the pop-up, you can use the unload
event of the window
object to detect the window closing or navigating to a new page, having previously recorded the time it opened at the the top of the document. For example:
<html>
<head>
<script type="text/javascript">
var start = new Date();
window.onunload = function() {
var end = new Date();
var secondsOpen = Math.floor((end - start) / 1000);
alert("Pop-up was open for " + secondsOpen + " seconds");
};
</script>
</head>
<body>
...
</body>
</html>
When it comes the calculating a certain time frame, I always use the date object, storing a new date in a variable once the popup is open and subtracting that value to the current date. Here's an example:
// Execute this when the popup opens
var popup_opened = (new Date()).getTime();
// And this way you can get the time (in seconds) that the popup has been opened
var current_time = (new Date()).getTime();
var time_spent_opened = (current_time - popup_opened)/100;
You can also retrieve the time the popup has been open multiple times using a function:
function getPopupTime() {
var current_time = (new Date()).getTime();
return (current_time - popup_opened)/100;
}
精彩评论