如何在JavaScript中制作计时器?

3
我想要一个会倒计时的会话超时计时器。我在CodePen上找到了一段代码,但它是顺时针计时器,我尝试将其变成逆时针,但未成功。请给我一些建议。我希望能够设置1小时或59分59秒的超时时间。请帮助我。 这里 是CodePen演示。
if((intervalCounter%1000)==0){
                currentTime += 1000;
                var appendHour = currentTime / (1000 * 60 * 60) | 0; 
                var appendMinute = currentTime % (1000 * 60 * 60) / (1000 * 60) | 0;
                var appendSecond = currentTime  % (1000 * 60) / 1000 | 0;

                appendHour = appendHour < 10 ? "0" + appendHour : appendHour;
                appendMinute = appendMinute < 10 ? "0" + appendMinute : appendMinute;
                appendSecond = appendSecond < 10 ? "0" + appendSecond : appendSecond;
                hour.html(appendHour);
                min.html(appendMinute);
                sec.html(appendSecond);

                }

搜索 setInterval()setTimeout() 函数。 - Spudley
1
请参考以下链接:https://stackoverflow.com/questions/26802817/clockwise-and-then-anticlockwise-rotation-in-javascript - Har devgun
1个回答

2
这段代码适用于逆时针方向。希望以下示例能为您提供一些思路。最初的回答:

此代码适用于逆时针方向。希望以下示例能为您提供一些思路。

// Set the date we're counting down to
var countDownDate = new Date("July 5, 2019 15:37:25").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();
    
  // Find the distance between now and the count down date
  var distance = countDownDate - now;
    
  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
  // Output the result in an element with id="demo"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";
    
  // If the count down is over, write some text 
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="demo"></p>


2
你可以检查一下这个链接:https://codepen.io/shivani30594/pen/ZdLGjo。请告诉我它是否对你有效。 - Shivani Sonagara
如果我想让它持续1个小时或59分钟:59秒。 - Every Thing
1
是的,差不多。从过去10天开始,我已经开始工作了,而且我很喜欢它。因此,我想每天都继续做。 :) - Shivani Sonagara
不错的尝试。如果我能解决您当前的问题,我会让您知道。谢谢! - Shivani Sonagara
干得好!!继续加油!! - user1630162
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接