使用jQuery的start-stop-reset简单计时器 [英] start-stop-reset simple timer using jQuery

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

问题描述

我有一个看起来像这样的代码

I have a code that looks like this

JS

var counter = 0;
var timer = setInterval("tictac()", 1000);

function tictac(){
    counter++;
    $("#clock").html(counter);
}

HTML

<div id="clock">0</div>
<div id="buttons" class="clear">
    <button id="start">start</button>
    <button id="stop">stop</button>
    <button id="reset">reset</button>
</div>

我该如何使用按钮控制计时器,按下开始按钮时开始计时,按下停止按钮时停止计时以及何时复位计数器按下重置按钮.

How can I make use of the buttons to control the timer, start counting up when start button is pressed, stop counting when stop button is pressed and reset counter when reset button is pressed.

有人可以帮忙吗?

我设法做到了

        $(document).ready(function($) {

            var timer = undefined;
            $('#start').on('click', function(){
                timer = window.setInterval('tictac()', 1000);
            });
            $('#pause').on('click', function(){
                window.clearInterval(timer);
            });
            $('#reset').on('click', function(){
                timer = window.clearInterval(timer);
            });

        });

        var counter = 0;
        function tictac(){
            counter++;
            $("#clock").html(counter);
        }

开始"和停止"按钮可以正常工作,但是重置无效,有人可以检查代码有什么问题吗?很好,请

The start and the stop buttons do the work, but the reset won't work, can some one check what's wrong with the code? pretty please

推荐答案

尝试 http://jsfiddle.net/vishalgupta358/DkTWN/

var counter = 0;
var timer = null;

function tictac(){
    counter++;
    $("#clock").html(counter);
}

function reset()
{
clearInterval(timer);
    counter=0;
}
function startInterval()
{
timer= setInterval("tictac()", 1000);
}
function stopInterval()
{
    clearInterval(timer);
}

这篇关于使用jQuery的start-stop-reset简单计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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