Javascript 倒计时器在窗口未处于焦点时停止

Sha*_*ady 1 javascript php countdown

好吧,我在解决这个问题时遇到了麻烦,我是一名 php / C# Web 开发人员,并且没有 Javascript 的经验或知识,我必须做这一件需要 Javascript 的事情:

当加载某个页面时,计数器就会启动。客户必须在此页面停留 20 秒。之后,我想执行php代码。

因此,有两个问题与我有关,第一:如果客户端离开页面(意味着页面没有焦点),我如何停止计数器。

2)如何在javascript中执行php?,或者从 Javascript 调用 php 函数。

到目前为止我的代码是这样的:

<html>
<head>
</head>

<body>
<div id='timer'>
<script type="text/javascript">

COUNTER_START = 20

function tick () {
    if (document.getElementById ('counter').firstChild.data > 0) {
        document.getElementById ('counter').firstChild.data = document.getElementById ('counter').firstChild.data - 1
        setTimeout ('tick()', 1000)
    } else {
        document.getElementById ('counter').firstChild.data = 'done'
    }
}

if (document.getElementById) onload = function () {
    var t = document.createTextNode (COUNTER_START)
    var p = document.createElement ('P')
    p.appendChild (t)
    p.setAttribute ('id', 'counter')

    var body = document.getElementsByTagName ('BODY')[0]
    var firstChild = body.getElementsByTagName ('*')[0]

    body.insertBefore (p, firstChild)
    tick()
}

</script>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我还希望计时器在客户端返回页面时开始计时

非常感谢您提前提供的帮助

Ter*_*ler 5

您可以使用 jQuery 来完成此操作。
回收旧的 Stackoverflow 帖子,试试这个:

var window_focus;
var counter = 1000;

// on focus, set window_focus = true.
$(window).focus(function() {
    window_focus = true;
});

// when the window loses focus, set window_focus to false
$(window).focusout(function() {
    window_focus = false;
});

// this is set to the ('click' function, but you could start the interval/timer in a jQuery.ready function: http://api.jquery.com/ready/
$(document).one('click',function() {
    // Run this function every second. Decrement counter if window_focus is true.
    setInterval(function() {
        $('body').append('Count: ' + counter + '<br>');
        if(window_focus) { counter = counter-1; }
    }, 1000);
});
Run Code Online (Sandbox Code Playgroud)

演示和旧帖子
演示| 老所以帖子

更新
可能是因为演示在 4 个 iframe 中运行,$(window).focus 位仅适用于实际运行代码的 iframe(右下窗口)。

jQuery
jQuery.com(jQuery 的工作原理) | 示例(回到页面中间的基础知识) | 如果您使用第二个链接,另请阅读此内容