[javascript] 가장 간단한 JavaScript 카운트 다운 타이머? [닫은]

가장 간단한 카운트 다운 타이머를 만드는 방법을 묻고 싶었습니다.

사이트에 다음과 같은 문장이 있습니다.

“등록은 05:00 분 안에 종료됩니다!”

그래서 내가하고 싶은 것은 “05:00″에서 “00:00″으로 이동 한 다음 “05:00″으로 재설정되는 간단한 js 카운트 다운 타이머를 만드는 것입니다.

나는 전에 몇 가지 대답을 겪었지만, 내가하고 싶은 일에 대해 너무 강렬하게 보입니다 (날짜 개체 등).



답변

나는 두 가지 데모를 가지고 있습니다 jQuery. 날짜 함수도 사용하지 않으며 간단합니다.

바닐라 JavaScript를 사용한 데모

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 5,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};
<body>
    <div>Registration closes in <span id="time">05:00</span> minutes!</div>
</body>

jQuery로 데모

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(minutes + ":" + seconds);

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

jQuery(function ($) {
    var fiveMinutes = 60 * 5,
        display = $('#time');
    startTimer(fiveMinutes, display);
});

그러나 약간 더 복잡한 타이머를 원한다면 더 복잡합니다.

function startTimer(duration, display) {
    var start = Date.now(),
        diff,
        minutes,
        seconds;
    function timer() {
        // get the number of seconds that have elapsed since 
        // startTimer() was called
        diff = duration - (((Date.now() - start) / 1000) | 0);

        // does the same job as parseInt truncates the float
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (diff <= 0) {
            // add one second so that the count down starts at the full duration
            // example 05:00 not 04:59
            start = Date.now() + 1000;
        }
    };
    // we don't want to wait a full second before the timer starts
    timer();
    setInterval(timer, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 5,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};
<body>
    <div>Registration closes in <span id="time"></span> minutes!</div>
</body>

이제 몇 가지 간단한 타이머를 만들었으므로 재사용 성 및 분리 문제에 대해 생각할 수 있습니다. “카운트 다운 타이머는 어떻게해야합니까?”

  • 카운트 다운 타이머가 카운트 다운되어야합니까?
  • 카운트 다운 타이머가 DOM에 자신을 표시하는 방법을 알아야합니까? 아니
  • 카운트 다운 타이머가 0에 도달하면 스스로 다시 시작해야합니까? 아니
  • 카운트 다운 타이머는 클라이언트가 남은 시간에 액세스 할 수있는 방법을 제공해야합니까?

따라서 이러한 점을 염두에두고 더 잘 작성하십시오 (하지만 여전히 매우 간단합니다). CountDownTimer

function CountDownTimer(duration, granularity) {
  this.duration = duration;
  this.granularity = granularity || 1000;
  this.tickFtns = [];
  this.running = false;
}

CountDownTimer.prototype.start = function() {
  if (this.running) {
    return;
  }
  this.running = true;
  var start = Date.now(),
      that = this,
      diff, obj;

  (function timer() {
    diff = that.duration - (((Date.now() - start) / 1000) | 0);

    if (diff > 0) {
      setTimeout(timer, that.granularity);
    } else {
      diff = 0;
      that.running = false;
    }

    obj = CountDownTimer.parse(diff);
    that.tickFtns.forEach(function(ftn) {
      ftn.call(this, obj.minutes, obj.seconds);
    }, that);
  }());
};

CountDownTimer.prototype.onTick = function(ftn) {
  if (typeof ftn === 'function') {
    this.tickFtns.push(ftn);
  }
  return this;
};

CountDownTimer.prototype.expired = function() {
  return !this.running;
};

CountDownTimer.parse = function(seconds) {
  return {
    'minutes': (seconds / 60) | 0,
    'seconds': (seconds % 60) | 0
  };
};

그렇다면 왜이 구현이 다른 구현보다 낫습니까? 여기 당신이 할 수있는 몇 가지 예가 있습니다. 첫 번째 예제를 제외한 모든 startTimer기능을 함수 로 수행 할 수는 없습니다 .

시간을 XX : XX 형식으로 표시하고 00:00에 도달 한 후 다시 시작하는 예

두 가지 형식으로 시간을 표시하는 예

두 개의 다른 타이머가 있고 한 번만 다시 시작하는 예

버튼을 눌렀을 때 카운트 다운 타이머를 시작하는 예


답변

실제 타이머를 원하면 날짜 객체를 사용해야합니다.

차이를 계산하십시오.

문자열을 포맷하십시오.

window.onload=function(){
      var start=Date.now(),r=document.getElementById('r');
      (function f(){
      var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
      r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
      if(diff>3e5){
         start=Date.now()
      }
      setTimeout(f,1e3);
      })();
}

JS 피들

정확하지 않은 타이머

var time=5*60,r=document.getElementById('r'),tmp=time;

setInterval(function(){
    var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
    r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
    tmp!=0||(tmp=time);
},1000);

JS 피들


답변

setInterval을 사용하여 타이머 기능을 쉽게 만들 수 있습니다. 아래는 타이머를 만드는 데 사용할 수있는 코드입니다.

http://jsfiddle.net/ayyadurai/GXzhZ/1/

window.onload = function() {
  var minute = 5;
  var sec = 60;
  setInterval(function() {
    document.getElementById("timer").innerHTML = minute + " : " + sec;
    sec--;
    if (sec == 00) {
      minute --;
      sec = 60;
      if (minute == 0) {
        minute = 5;
      }
    }
  }, 1000);
}
Registration closes in <span id="timer">05:00<span> minutes!


답변