2012-10-25 82 views
0

我有一些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變量時,它似乎不起作用。

+1

上的代碼2號線錯字'indow.'應該是'window.' – Scott

+0

嗨,我已籤實際的代碼。實際的代碼沒有錯字。我意外地在複製粘貼堆棧溢出時犯了一個錯字。 – Ferrino

+0

您是否考慮過[setInterval](https://developer.mozilla.org/en-US/docs/DOM/window.setInterval)函數進行計時? – undefined

回答

2

您的HTML代碼將設置isTimerOn = true,僅限表單提交。 也許這不是你想要的。

提交表單也會將當前頁面更改爲mainheader.jsp,並通過ProcessThisSearch函數加載另一個頁面。

可能的修復將是:

<button onClick="ProcessThisSearch(this.form)">Open Website</button>

OR

<form align=right action="mainheader.jsp" method="POST"><input type="text" name="search"><input type="submit" value="Open Website" onClick="ProcessThisSearch(this.form);return false;"></form>

+0

你好anishsane,非常感謝你的幫助。解決方案似乎工作。只是我的理解幾個問題: 如何在窗體中返回false的幫助? – Ferrino

+0

*一般*,任何onclick事件的「返回false」將中止點擊的正常效果。例如對於'a'元素,它會中止鏈接導航,對於表單的input type = submit元素,它會中止表單提交。 onclick中的代碼(您的示例中的ProcessThisSearch)將被執行。 – anishsane