添加开始停止和重置按钮jquery

时间:2011-04-30 23:46:29

标签: jquery timer

如何在倒数计时器中添加开始,停止和重置按钮

var cycle = 0;


    function countdown()
    {
        var min = 60*5;
        var max = 60*7;

        return Math.floor(Math.random()*max) + min;
    }


    function search()
    {
        $.getJSON('json', function(data)
            {
                $('#fullurl').attr("src", 'mywebsite' + data);
            }
        );
    }


    function update()
    {
        if (cycle == 0)
        {
            cycle = countdown();
            search();

            $('#countdown').html('...');
        }
        else 
        {
            var minutes = Math.floor(cycle / 60);
            var seconds = (cycle % 60);

            if (seconds < 10) seconds = "0" + seconds;

            $('#countdown').html(minutes + ':' + seconds);

            cycle--;
        }

        setTimeout('update()', 1000);
    }

1 个答案:

答案 0 :(得分:3)

我在上面的代码中看不到任何HTML标记,对我来说看起来有点神秘和不完整。我的猜测是在开始上致电update(),在停止时取消暂停,并在重置时重置变量。

var cycle = 0;
var timer_id = null;

function countdown()
{
    var min = 60*5;
    var max = 60*7;

    return Math.floor(Math.random()*max) + min;
}


function search()
{
    $.getJSON('json', function(data)
        {
            $('#fullurl').attr("src", 'mywebsite' + data);
        }
    );
}


function update()
{
    if (cycle == 0)
    {
        cycle = countdown();
        search();

        $('#countdown').html('...');
    }
    else 
    {
        var minutes = Math.floor(cycle / 60);
        var seconds = (cycle % 60);

        if (seconds < 10) seconds = "0" + seconds;

        $('#countdown').html(minutes + ':' + seconds);

        cycle--;
    }

    timer_id = setTimeout('update()', 1000);
}

function stop()
{
    if(timer_id)
    {
        clearTimeout(timer_id);
        timer_id = null;
    }
}

function reset()
{
    stop();
    cycle = 0;

    //reset your HTML elements, just guessing
    $('#countdown').html('');
    $('#fullurl').attr("src", '');
}

//jQuery ready function
$(function(){
    //assuming you add some buttons with IDs to your markup
    $('#btnStart').click(update);
    $('#btnStop').click(stop);
    $('#btnReset').click(reset);
});