JavaScript启动和停止计时

时间:2012-10-25 12:38:32

标签: 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变量是一个标志,它将在以下时间设置:

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(表单)将以下列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变量时,它似乎才起作用。

1 个答案:

答案 0 :(得分: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>

相关问题