我对 JavaScript 计时有一些问题..基本上我希望它在失去焦点时开始计时,当它回到焦点时,计时将停止并显示。
var start,end,isTimerOn=0;
window.addEventListener('blur', function() { //when user get out of the screen
/*Start Time when user goes out of focus*/
start = new Date().getTime();
});
window.addEventListener('focus', function() { //when user focus on the screen
if (isTimerOn==1)
{
end = new Date().getTime();
var time = end - start; //time will be in ms. eg: 1 sec will be 1000
/*Convert to seconds*/
var y=Math.round(time/1000);
start=0; //reset
isTimerOn=0; //reset
alert('Execution time: ' + y + 'secs'); //this will print the time how long the user has been away
}
});
现在 isTimerOn 变量是一个标志,将在以下情况下设置:
function ProcessThisSearch(form)
{
//alert("OI!"); //test is js is working.
var test=form.search.value;
//alert(test); //test if value can be retrieved
if (test)
{
isTimerOn=1;
window.open('http://www.'+test+'.com');
}
}
此函数 ProcessThisSearch(form) 将在以下 HTML 表单中调用:
<form align=right action="mainheader.jsp" method="POST"><input type="text" name="search"><input type="submit" value="Open Website" onClick="ProcessThisSearch(this.form)"></form>
我相信问题出在 isTimerOn 变量上。因为我已经测试了两个事件监听器并且它正在工作。只有当我添加 isTimerOn 变量时,它似乎不起作用。