开发者

onfocus / onblur progress

Hello I'm newbie in javascript and worked hard today on this and couldn't find the solution. Please help me.

<script>
    if (/*@cc_on!@*/false) {
        document.onfocusin = startB;
        document.onfocusout = stopB;
    } else {
        window.onfocus = startB;
        window.onblur = stopB;
    }

var x = 1000;
var y = 1;

function startB() {
    if (x !== 'ok') {
        x = x - y;
        document.form.num.value = x;
        timeoutID=setTimeout("startB()", 1000);
    } 
    if (x == 0) {
        x = 'ok';
        document.form.num.value = x;
    }
}

function stopB() {
clearTimeout(timeoutID);
}
</script>
<body onLoad="startB()">
<form name="form">
<input name="num" size="10" readonly="readonly" type="text"> 
</form>

When I open this page it counts down with value 1/sec normally and when I change window/tab it stops, I again come back it's continues 1/sec, this is what I want, but I have a big problem --> When I go to this link and change window/tab very quickly, that is still unloaded, it starts counting down in onblur status, and when I come back to onfocus status, the function is read twice and starts counting down 1/0.5sec... double.

Can anyone help me with this? Thank开发者_开发技巧s in advance.


Have startB call stopB before it sets the timeout. Change stopB to:

  if (timeoutID) clearTimeout(timeoutID);

so that if the timeoutID has already been cleared (or not set yet) it won't throw an error.

Edit

If you navigate away from the page before the load event occurs, then the timer will start without the page getting focus. If you cancel the timeout before setting it (i.e. startB always calls stopB before calling setTimeout), you can't have two timers running.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜