开发者

How to trigger a setInterval function on a user click?

开发者 https://www.devze.com 2023-03-07 15:11 出处:网络
I\'m trying to write a JS timer that will be triggered by a user click on the button with id=\"start\".

I'm trying to write a JS timer that will be triggered by a user click on the button with id="start".

I've got the timer itself working correctly, but when I try to add code to initiate the timer on the button click (id="start") I break it and am not sure why.

Any help would be greatly appreciated!

Here is the JS code:

    $(document).ready(function(){

    var count = 0;

        $('#start').click(function(){
            setInterva开发者_Go百科l(function(){
                count++;
                $('#timer').html(count + ' tacos seconds');
            },1000);
        });

    });


$(document).ready(function() {
    $('#start').click((function(container) {
        var interval;
        return function() {
            if(interval) clearInterval(interval);

            var count = 0;

            interval = setInterval(function() {
                count++;
                $(container).html(count + ' tacos seconds');
            }, 1000);
        };
    })("#timer"));
});


$(document).ready(function() {
  var count = 0;
  var myInterval = null;
  $('#start').click(function(){
      myInterval = setInterval(function(){
        count++;
        $('#timer').html(count + ' tacos seconds');
      },1000);
  });

});

When setting your setInterval in the scope of the click handler, try assigning it to a variable to hold the interval declared up a level. This has typically always worked for me.


Not sure exactily what your objective is, but maybe you'd want to try something like this:

var startInterveal;
var timerStarted = false;
var count =0;
$(document).ready(function () {
    $('#start').click(function () {
        if (!timerStarted) {
            timerStarted = true;
            count =0;
            $(this).attr('disabled', 'disabled');
            startInterveal = setInterval('tick();', 1000);
        }
    });
});

function tick() {
    count++;
    $('#timer').html(count + ' tacos seconds');
}


Here is a 2nd answer if you really want to go nuts and have something resuable:

$(document).ready(function() {
    $('#start').click(overboard("#timer"));
    $('#start2').click(overboard("#timer2"));
});

function overboard(container) {
    var interval;
    return function() {
        if (interval) clearInterval(interval);

        var count = 0;

        interval = setInterval(function() {
            count++;
            $(container).html(count + ' tacos seconds');
        }, 1000);
    };
}
0

精彩评论

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

关注公众号