jQuery Countdown Each Second

2019-10-03 06:15发布

I'm trying to make a jQuery countdown type animation, that once it hits 0 it executes a function. However I'm having problems because I'm unsure how to go about doing this. I thought I'd do a while loop then pause for a second until it hits 0. However it doesn't seem possible to pause a while loop. So I'm wondering what's the best way to do this? Thanks.

6条回答
Deceive 欺骗
2楼-- · 2019-10-03 06:44

Try this out. It does not require jQuery.

var count = 5;  // Number of times to run 'counter_function'.

// Run 'counter_function' every second (1000ms = 1 second)
var counter = setInterval(function(){
    counter_function()
}, 1000);

// The function to run when 'count' hits 0.
var done_function = function() {
    console.log('done');
}

// The function to run at each interval.
var counter_function = function() {
    console.log('count');
    count--;

    if(count === 0){
        done_function();
        clearInterval(counter);
    }
}

It will print the word 'count' every second for 5 seconds, and at the last second it will also print 'done'.

查看更多
戒情不戒烟
3楼-- · 2019-10-03 06:46

I would use something like the following :

 $(document).ready(function(){
  var counter=10;
  countDown();

  function countDown(){

    $('#showNumber').text(counter--);
    if(counter>=0) 
      window.setTimeout(countDown,1000)
    else
      otherFunction();
  }

  function otherFunction(){
     $('#showNumber').text('FINISHED!');
  }

});
查看更多
唯我独甜
4楼-- · 2019-10-03 07:00

Code:

var counter = 10;
var yourFunc = function(){}
var interval = setInterval(function(){
    counter--;
    if(counter <=0){ yourFunc(); clearInterval(interval); }
}, 1000);
查看更多
爷的心禁止访问
5楼-- · 2019-10-03 07:02
  • countdown takes an HTMLElement to display itself and the number of seconds to count down for

  • It returns a Promise that resolves when the counter reaches 0

  • We can use a .then call to apply a function when the count-down has completed

function countdown(elem, s) {
  return new Promise(function(resolve) {
    function loop(s) {
      elem.innerHTML = s
      if (s === 0)
        resolve(elem)
      else
        setTimeout(loop, 1000, s - 1)
    }
    loop(s)
  })
}
                     
countdown(document.querySelector('#a'), 3).then(
  function(elem) { console.log('done', elem) }
)

countdown(document.querySelector('#b'), 5).then(
  function(elem) { console.log('done', elem) }
)

countdown(document.querySelector('#c'), 10).then(
  function(elem) { console.log('done', elem) }
)
<p id="a"></p>
<p id="b"></p>
<p id="c"></p>

You should also be aware that setTimeout and setInterval do not guarantee that the milliseconds argument used is 100% accurate …

var last = Date.now()
var interval = setInterval(function() {
  var now = Date.now()
  var delta = now - last
  console.log(delta)
  last = now
}, 1000)

setTimeout(clearInterval, 10000, interval)
// 1000
// 1003
// 998
// 1002
// 999
// 1007
// 1001
// ... 

If you need a long running timer with high accuracy, I recommend you adapt the solution to use delta-based updates to the clock. If you rely upon setTimeout or setInterval for accuracy, you will be sad.

function countdown(elem, ms) {
  return new Promise(function(resolve) {
    function loop(ms, last) {
      let now = Date.now()
      let delta = now - last
      if (ms <= 0) {
        elem.innerHTML = 0
        resolve(elem)
      }
      else {
        elem.innerHTML = (ms/1000).toFixed(3)
        setTimeout(loop, 25, ms - delta, now)
      }
    }
    loop(ms, Date.now())
  })
}
                     
countdown(document.querySelector('#a'), 3000).then(
  function(elem) { console.log('done', elem) }
)

countdown(document.querySelector('#b'), 5000).then(
  function(elem) { console.log('done', elem) }
)

countdown(document.querySelector('#c'), 10000).then(
  function(elem) { console.log('done', elem) }
)
<p id="a"></p>
<p id="b"></p>
<p id="c"></p>

查看更多
淡お忘
6楼-- · 2019-10-03 07:03

Are you looking for something like this OP?

This executes every second. You can use clearInterval() just as I added in the comment section whenever you want it to stop.

var start = 10; // time to countdown from in seconds
var interval = setInterval(
  function(){ 
    if (start == 0) {
      complete();
      clearInterval(interval);
    }
    $(".update").html("<h4>Countdown "+start+"</h4>");
    start--;
  }, 1000);

function complete() {
  console.log("called the callback, value of start is: "+start);  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="update">
  
</div>

查看更多
该账号已被封号
7楼-- · 2019-10-03 07:04

I would use a recursive function

var countDown = function(secondsRemaining){
    secondsRemaining -= 1;
    if(secondsRemaining <= 0){
        //execute
    } else {
        //wait 1 second and call again
        setTimeout(function(){
            countDown(secondsRemaining);
        }, 1000);
    }
}

then to initially start countdown (5 seconds)

countDown(5000);
查看更多
登录 后发表回答