How to trigger a setInterval function on a user click?

蓝咒 提交于 2019-12-04 07:09:51

问题


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(){
            setInterval(function(){
                count++;
                $('#timer').html(count + ' tacos seconds');
            },1000);
        });

    });

回答1:


$(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"));
});



回答2:


$(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.




回答3:


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');
}



回答4:


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);
    };
}


来源:https://stackoverflow.com/questions/6076746/how-to-trigger-a-setinterval-function-on-a-user-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!