HTML代码:
<body class="body" onload="buttonFunction(this)">
<form>
<p align="center"><strong>You have been on this page for </strong><input title="time spent on webpage" type="text" size="9" name="timespent"></p>
</form>
</body>JS代码:
function buttonFunction() {
startday = new Date();
clockstart = startday.getTime();
initstopwatch();
getSecs();
}
function initstopwatch() {
var mytime = new Date();
var timeNow = mytime.getTime();
var timediff = timeNow - clockstart;
this.diffsecs = timediff/1000;
return(this.diffsecs);
}
function getSecs() {
var mySecs = initstopwatch();
var mySecs1 = ""+mySecs;
mySecs1= mySecs1.substring(0,mySecs1.indexOf("."))+ " secs. ";
document.forms[0].timespent.value = mySecs1;
window.setTimeout('getSecs()',1000);
}现在,这个函数应该计算用户在我的网页上的秒数,并将该变量输入到输入框中。然而,它似乎什么也做不了。那么这个函数有什么问题呢?
发布于 2017-01-19 01:39:40
所以,让我们从头开始,因为我可以用这种方式解释更多的事情。
首先,我们需要节省用户到达页面的时间。我们可以通过保存页面加载后的日期来做到这一点。
// The variable is outside because we need every function to
// be able to access it (like a global variable)
var userArrived;
// The function to initialize the counter
function initCounter(){
// Get the date when the user arrived
// here we do not use `var` because the variable exists
userArrived = new Date().getTime(); // This returns the date in milliseconds
}
// Wait the page to load
window.addEventListener('load', function(){
// Initialize the counter
initCounter();
}, false);现在我们需要一个函数来给我们区别
function getCounterValue(){
// Calculate difference
var value = new Date().getTime() - userArrived;
// This variable now have the time the user
// is on the page in milliseconds
// Now we need to return the value to the caller
return value;
}现在我们可以获得毫秒了,我们需要一个函数将它们解析为人类可读的格式。
function parseMs2Sec(ms){
// We calculate seconds using seconds = milliseconds / 1000
// but we round it so that we don't have decimals
var sec = Math.round(ms/1000);
// Now we need to return the value to the caller
return sec;
}现在唯一要做的事情就是每1秒(或更多)更新我们需要的任何可视元素。
// Save the element on a variable for easy access
var timeSpent = document.forms[0].timespent;
// Update the screen with the latest time
function updateScreeenCounter(){
// Get the time the user is in the page
var ms = getCounterValue();
// Convert it to seconds
var sec = parseMs2Sec(ms);
// Display it in the page
timeSpent.value = sec + " sec.";
}
// Every 1000 milliseconds
setInterval(function(){
// Run function
updateScreeenCounter();
}, 1000);
// But this last code (with the interval)
// needs to run after the counter was initialized
// so we should put it inside the onload event we created.下面是演示中的漏洞代码:
//
// The variable is outside because we need every function to
// be able to access it (like a global variable)
var userArrived;
// The function to initialize the counter
function initCounter(){
// Get the date when the user arrived
// here we do not use `var` because the variable exists
userArrived = new Date().getTime(); // This returns the date in milliseconds
}
// Gives back the time since the user arrived on page (in ms)
function getCounterValue(){
// Calculate difference
var value = new Date().getTime() - userArrived;
// This variable now have the time the user
// is on the page in milliseconds
// Now we need to return the value to the caller
return value;
}
// Converts the given ms in the closest seconds
function parseMs2Sec(ms){
// We calculate seconds using seconds = milliseconds / 1000
// but we round it so that we don't have decimals
var sec = Math.round(ms/1000);
// Now we need to return the value to the caller
return sec;
}
// Update the screen with the latest time
function updateScreeenCounter(){
// Get the time the user is in the page
var ms = getCounterValue();
// Convert it to seconds
var sec = parseMs2Sec(ms);
// Display it in the page
document.forms[0].timespent.value = sec + " sec.";
}
// Wait the page to load
window.addEventListener('load', function(){
// Initialize the counter
initCounter();
// Every 1000 milliseconds
setInterval(function(){
// Run function
updateScreeenCounter();
}, 1000);
}, false);<form>
<input name="timespent" value="Loading ..."/>
</form>
还有一些小贴士:
~编辑~
我忘记提到在这种情况下使用setInterval更好,因为它比慢计算机中的递归setTimeout更精确。
发布于 2017-01-19 00:24:08
根据他那斯·格莱马托普洛斯的评论,我先前的回答(以下)是错误的。我试图通过修复分号定位来运行您的代码,它在Safari中运行。
window.setTimeout('getSecs()',1000; ) 应该是
window.setTimeout('getSecs()',1000);我以前不正确的答案:setTimeout只会调用getSecs()一次。我认为您希望每秒调用它一次,而不是一秒调用一次,在这种情况下,您应该使用:
window.setInterval(getSecs,1000);如果您想在稍后停止间隔(可能是个好主意),您可以这样做:
var interval = window.setInterval(getSecs,1000);稍后,当您希望停止计时器时,只需调用:
clearInterval(interval);发布于 2017-01-19 00:24:54
基本上,应该将setTimeout替换为setInterval (因为您希望重复调用getSecs,而不仅仅是一次)。然后,您希望传递给它的是对函数的引用,而不是它的调用,因此getSecs (没有引号或括号)而不是"getSecs()"。很可能这就是原因。我现在无法测试代码。但问题是,getSecs()不应该自称,因为它将取决于setInterval
第二,代码应该得到一个巨大的清理,但我将能够提供更多的帮助,明天,如果没有人提出一个很好的重构。
https://stackoverflow.com/questions/41731673
复制相似问题