我有一些JavaScript時序問題..基本上我希望它開始計時,當它失去焦點,當它回到焦點時,計時將停止並顯示。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變量是其將在何時設置一個標誌:
<form align=right action="mainheader.jsp" method="POST"><input type="text" name="search"><input type="submit" value="Open Website" onClick="ProcessThisSearch(this.form)"></form>
I:將在下面的HTML表單調用
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(形式)的相信問題出在isTimerOn變量上。因爲我測試了兩個事件監聽器並且它正在工作。只有當我添加isTimerOn變量時,它似乎不起作用。
上的代碼2號線錯字'indow.'應該是'window.' – Scott
嗨,我已籤實際的代碼。實際的代碼沒有錯字。我意外地在複製粘貼堆棧溢出時犯了一個錯字。 – Ferrino
您是否考慮過[setInterval](https://developer.mozilla.org/en-US/docs/DOM/window.setInterval)函數進行計時? – undefined