Home > Net >  Public plugin methods issue
Public plugin methods issue

Time:12-21

I use this code (https://github.com/rendro/countdown) and I am running into an issue.

Specifically, I am launching a countdown timer like this:

$('.countdown').countdown({
            date: new Date().getTime()   (1000 * 60 * minutes - 1000),
            render: function(data) {
            $(this.el).text(this.leadingZeros(data.min)   ":"   this.leadingZeros(data.sec, 2));
}
});

Afterwards, I am using the restart() method like so:

$('.countdown').data('countdown').restart({
            date: new Date().getTime()   (1000 * 60 * minutes - 1000),
            render: function(data) {
            $(this.el).text(this.leadingZeros(data.min)   ":"   this.leadingZeros(data.sec, 2));
            }
        });

Now I am trying to use the "stop()" method, but can't figure out how I should be doing it.

If I use $('.countdown').data('countdown').stop(); right after I start the timer, it works.

However, If I run that same command after I have used restart(), then it doesn't work. More specifically, it keeps refreshing the timer until it reaches 0 (even if I have used stop() ).

Any idea why?

CodePudding user response:

It looks like the stop method is not designed to stop a countdown timer that has been restarted using the restart method. Instead, the stop method simply removes the countdown timer from the page and removes the countdown data from the element.

To stop a countdown timer that has been restarted using the restart method, you will need to implement your own custom solution. One approach you could try is to store a flag in your code that indicates whether the countdown timer is currently running or stopped. You can then check this flag in the render callback function to determine whether to update the timer display or not.

For example:

var countdownRunning = true;

$('.countdown').countdown({
  date: new Date().getTime()   (1000 * 60 * minutes - 1000),
  render: function(data) {
    if (countdownRunning) {
      $(this.el).text(this.leadingZeros(data.min)   ":"   this.leadingZeros(data.sec, 2));
    }
  }
});

$('.countdown').data('countdown').restart({
  date: new Date().getTime()   (1000 * 60 * minutes - 1000),
  render: function(data) {
    if (countdownRunning) {
      $(this.el).text(this.leadingZeros(data.min)   ":"   this.leadingZeros(data.sec, 2));
    }
  }
});

function stopCountdown() {
  countdownRunning = false;
  $('.countdown').data('countdown').stop();
}

With this approach, calling the stopCountdown function will stop the countdown timer by setting the countdownRunning flag to false and calling the stop method. The render callback function will then check the value of the countdownRunning flag before updating the timer display, preventing the countdown timer from being updated.

  • Related