javascript计时器 [英] javascript timer

查看:33
本文介绍了javascript计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过单击一个按钮使以下javascript计时器执行两项功能-计时器启动后单击;再次点击;它停止了.单击第三次它再次开始,依此类推.我在这里做错了什么?提前非常感谢您.

I am trying to make the following javascript timer perform two functions with a click of one button only - click once the timer starts; click again; it stops. click a third time it starts again, and so forth. What am I doing wrong in here? Thank you very much in advance.

    <html>
<head>
    <script type="text/javascript">
        var c=0;
        var t;
        var timer_is_on=0;

        function timedCount()
        {
            document.getElementById('txt').value=c;
            c=c+1;
            t=setTimeout("timedCount()",1000);
        }

        function doTimer()
        {
            if (!timer_is_on)
            {
                timer_is_on=1;
                timedCount();
            }
        }

        function stopCount()
        {
            clearTimeout(t);
            timer_is_on=0;
        }
        function both(){
            doTimer();
            stopCount();
        }
    </script>
</head>

<body>
    <form>
        <input type="button" value="Start count!" onclick="doTimer" />
        <input type="text" id="txt" />
        <input type="button" value="Stop count!" onclick="stopCount()" />
    </form>
<p>
Click on the "Start count!" button above to start the timer. The input field will count forever, starting at 0. Click on the "Stop count!" button to stop the counting. Click on the "Start count!" button to start the timer again.
</p>
</body>
</html>

推荐答案

您没有描述一个实际的问题,因此我不确定该如何处理,但是这里有一些可能有用的注释.

You don't describe an actual problem, so I'm not quite sure what to respond with, but here's a couple of potentially helpful notes.

timedCount函数是准定时递归的.如果您喜欢连续传递样式,这很酷,但是这不是必需的,可能是比JavaScript所需要的混乱得多,并且会浪费一些没有尾递归堆栈清理(不知道JS是否具有)的语言的资源(堆栈框架).

The timedCount function is quasi-timed-recursive. This is cool if you're into continuation passing style, but it's not necessary, probably a little more confusing than it needs to be for JavaScript, and will waste some resources (stack frames) in languages that don't have tail-recursive stack cleanups (don't know if JS has that or not).

由于这是重复执行函数,因此可以使用 setInterval 而不是 setTimeout ,并且有一个重复的函数调用,检查它是否应该增加并重新显示计数...类似这样:

Since this is a repeating function execution, you could use setInterval instead of setTimeout, and have a single repeated function call that checks to see if it should increment and re-display the count... something like this:

var c=0;
var timer_is_on=false;

function displayCount() {
    document.getElementById('txt').value=c;
}

function count() {
    if(timer_is_on) {
        c=c+1;
        displayCount();
    }
}

var interval = setInterval(count,1000);

现在,解决问题的单键部分.假设有一个按钮:

Now, to address the single-button part of the problem. Let's say there's a single button:

<input type="button" value="Start count!" onclick="toggle" />

当我们单击它时,我们希望该值"属性发生变化,并且希望它翻转 timer_is_on 变量.让我们创建一个执行所有这些操作的函数:

When we click on it, we want that "value" attribute to change, and we want it to flip the timer_is_on variable. Let's create a function that does all these things:

function toggle() {
    if(timer_is_on) {
       timer_is_on = false;
       this.value = "Start count!";  // `toggle` is invoked by the button's event handler, so `this` is the button
    } else {
       timer_is_on = true;
       this.value = "Stop count!";
    }                   
}

所以...计数总是每1000毫秒执行一次,但仅在timer_is_on上执行任何操作,并且timer_is_on是true还是false都由附加在按钮上的 toggle 控制.我想有点简单.

So... count is always executing every 1000ms, but it only does anything if timer_is_on, and whether or not timer_is_on is true or false is controlled by toggle, which is attached to our button. Little bit simpler, I think.

更新

如果我们不想 count 函数始终在后台运行怎么办?正如Tom Tu指出的那样,这可能代表CPU开销.我不确定这是可以衡量的(或者它代表了浏览器可能正在运行以进行自己的UI更新的计时器之外的任何开销),但是它在某些平台上可能很重要,因此可能值得解决.

What if we wanted to not have the function count always running in the background? As Tom Tu points out, this may represent a CPU overhead. I'm not certain it's a measurable one (or that it represents any overhead beyond the timer the browser is probably running to do its own UI updates), but it could be important on some platforms and so it's probably worth addressing.

我们在完善的同时,我不喜欢自己通过标签属性附加事件处理程序,或者如果可以避免的话,不希望将变量放在global/window范围内,所以我可能会包装所有相关的计数器设置/在一个大型 setupCounter 函数中处理JavaScript,并使用DOM选择和JavaScript将 toggle 函数附加到输入按钮的 onclick 事件.我可能也尝试只运行一次 document.getElementById 查找.

While we're polishing, I don't much like attaching event handlers through tag attributes myself, or putting variables in the global/window scope if I can avoid it, so I'd probably wrap all our relevant counter setup/processing JavaScript inside one big setupCounter function, and also attach the toggle function to the onclick event of the input button using DOM selection and JavaScript. I'd probably try to only run the document.getElementById lookups once each, too.

因此,假设按钮输入的ID为 startstop ,但其他情况下则采用类似的标记.我可能会做这样的事情:

So, let's say the button input has the id startstop but otherwise assume similar markup. I'd probably do something like this:

function setupCounter() { 
    var c=0,
        interval,
        counter_display = document.getElementById('txt'),
        button = document.getElementById('startstop');

    function display_count() {
        counter_display.value = c;
    }

    function count() {
        c=c+1;
        display_count();
    }

    function toggle() {
       if(!interval)
          interval = setInterval(count,1000);
          button.value = "Stop count!";
       else {
          clearInterval(interval);
          interval = false;
          button.value = "Start count!";
       }
    }

    button.onclick = toggle;
}

然后您要么在声明了counter_display和startstop元素之后的某个时间在文档中调用 setupCounter ,要么将其分配给 window.onload 事件或传递类似于jQuery的 $(document).ready().

Then you'd call setupCounter either sometime in the document after both the counter_display and startstop elements have been declared, or assign it to the window.onload event or pass it to something like jQuery's $(document).ready().

这篇关于javascript计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆