在警报框中创建返回倒数计时器

时间:2014-02-28 05:39:42

标签: javascript jquery asp.net-mvc-3 logic countdowntimer

我需要创建一个计时器,它将显示在javascript的警告框中,它将从4分钟开始倒计时到0 ..当场时间结束,它应该停止计时器。我想要的一切都是在Javascript中创建的。我尝试过以下从此链接获得的代码: Timer in Javascript

但它不适合我。我做了这个::

<script>
     window.onload = CreateTimer("timer", 30);
        var Timer;
        var TotalSeconds;
        function CreateTimer(TimerID, Time) {

            Timer = document.getElementById(TimerID);
            TotalSeconds = Time;
            UpdateTimer()
            window.setTimeout("Tick()", 1000);
        }

        function Tick() {
            if (TotalSeconds <= 0) {
                alert("Time's up!")
                return;
            }
            TotalSeconds -= 1;
            UpdateTimer()
            window.setTimeout("Tick()", 1000);
        }

        function UpdateTimer() {
            var Seconds = TotalSeconds;

            var Days = Math.floor(Seconds / 86400);
            Seconds -= Days * 86400;

            var Hours = Math.floor(Seconds / 3600);
            Seconds -= Hours * (3600);

            var Minutes = Math.floor(Seconds / 60);
            Seconds -= Minutes * (60);


            var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)


            Timer.innerHTML = TimeStr;
        }


        function LeadingZero(Time) {

            return (Time < 10) ? "0" + Time : +Time;

        }
</script>


 <div class="page">


        <div id='timer' style="float: left; width: 50%; background-color: red; color: white;"></div>

</div>

1 个答案:

答案 0 :(得分:0)

我希望,它会对你有所帮助。

    window.onload = CreateTimer("timer", 30);
      var Timer;
      var TotalSeconds;
      function CreateTimer(TimerID, Time) { 
        Timer = document.getElementById(TimerID);
        TotalSeconds = Time;
        UpdateTimer()
        window.setTimeout(Tick, 1000); // remove double quote
      }

      function Tick() {
        if (TotalSeconds <= 0) {
        alert("Time's up!")
        return;
      }
      TotalSeconds -= 1;
      UpdateTimer()
      window.setTimeout(Tick, 1000); // remove double quote
   }

   function UpdateTimer() {
      var Seconds = TotalSeconds;

      var Days = Math.floor(Seconds / 86400);
      Seconds -= Days * 86400;

      var Hours = Math.floor(Seconds / 3600);
      Seconds -= Hours * (3600);

      var Minutes = Math.floor(Seconds / 60);
      Seconds -= Minutes * (60);


      var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" +        LeadingZero(Minutes) + ":" + LeadingZero(Seconds)


      Timer.innerHTML = TimeStr;
   }


  function LeadingZero(Time) {

      return (Time < 10) ? "0" + Time : +Time;

  }

评论是我做过更改的地方。此外,您还需要根据要求修改代码,因为当秒数等于0时,无论时间是否剩余,都会显示警报消息。我不知道你对此的要求我没有碰到那个代码。 请点击此链接查看live demo