Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

javascript - jQuery Countdown Each Second

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...