最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Extend timeout function when button is clicked - Stack Overflow

programmeradmin2浏览0评论

This piece of code works, but I am trying to get the timeout function to reset to '0' every time the button is clicked.

var running = false,
    count = 0,
    run_for = 700;


var end_counter = function() {
    if (running) {
        running = false;
        $("#status").text("Not Running");
        alert(count);
        started_at = 0;
    }
};

$('button').click(function() {
    if (running) {
    count++;


    } else {
        running = true;
        $("#status").text("Running");
        count = 1;
        setTimeout(end_counter, run_for);
    }
});

This piece of code works, but I am trying to get the timeout function to reset to '0' every time the button is clicked.

var running = false,
    count = 0,
    run_for = 700;


var end_counter = function() {
    if (running) {
        running = false;
        $("#status").text("Not Running");
        alert(count);
        started_at = 0;
    }
};

$('button').click(function() {
    if (running) {
    count++;


    } else {
        running = true;
        $("#status").text("Running");
        count = 1;
        setTimeout(end_counter, run_for);
    }
});
Share Improve this question asked Jul 18, 2014 at 1:00 neobianneobian 411 silver badge2 bronze badges 2
  • Google for a "debounce" keyword. Some random link: benalman./code/projects/jquery-throttle-debounce/examples/… Another random link: davidwalsh.name/javascript-debounce-function – zerkms Commented Jul 18, 2014 at 1:02
  • I wish to count the number of times the button is clicked, but I want it to extend the time you can click it after each click, if that helps explain it better. – neobian Commented Jul 18, 2014 at 1:02
Add a ment  | 

2 Answers 2

Reset to default 7

Just cancel and restart it:

var timerId,
    count = 0;
function end_counter() {
    $("#status").text("Not Running");
    alert(count);
    count = 0;
}
$('button').click(function() {
    $("#status").text("Running");
    count++;
    clearTimeout(timerId);
    timerId = setTimeout(end_counter, 700);
});
var running = false,
    count = 0,
    run_for = 700;

var timer;

var end_counter = function() {
    if (running) {
        running = false;
        $("#status").text("Not Running");
        alert(count);
        started_at = 0;
    }
};

$('button').click(function() {
    clearTimeout(timer);
    if (running) {
        count++;
        timer = setTimeout(end_counter, run_for);
    } else {
        running = true;
        $("#status").text("Running");
        count = 1;
        timer = setTimeout(end_counter, run_for);
    }
});

Set timer to a variable - then clear it on click and restart it after count.

发布评论

评论列表(0)

  1. 暂无评论