简体   繁体   English

制作倒数计时器,将时间存储在变量中

[英]Make a countdown timer where time stored is in a variable

I have a variable in JavaScript storing time. 我在JavaScript存储时间中有一个变量。 For example, duration is a variable that stores time in minutes and hours as in 14 minutes or 1 hour 20 minutes. 例如, duration是一个变量,以分钟和小时为单位存储时间,如14分钟或1小时20分钟。 How do I make a countdown timer using this variable in JavaScript? 如何在JavaScript中使用此变量制作倒数计时器?

One way to do it would be to extract the desired values with a regular expression and to use setInterval() to call a function to periodically update the timer. 一种方法是使用正则表达式提取所需的值,并使用setInterval()调用函数以定期更新计时器。

The following expression matches your pattern : 以下表达式与您的模式匹配:

/^\s*(?:(\d+)\s+hour(?:s)?\s*)?(\d+)\s+minute(?:s)?$/i

The first capture group will give you the number of hours and the second one the number of minutes. 第一个捕获组将为您提供小时数,第二个捕获组将为您提供分钟数。 You can access them thanks to the match method. 您可以通过match方法访问它们。 That will return you an array containing the matches with one item per match (or null if no match is found). 这将返回一个包含匹配项的数组,每个匹配项只有一项(如果找不到匹配项,则为null )。

You can then get h and m , respectively the number of hours and the munber of minutes like this 然后,您可以分别获得hm ,例如小时数和分钟数

time  = "1 hour 10 minute";
match = time.match(/^\s*(?:(\d+)\s+hour(?:s)?\s*)?(\d+)\s+minute(?:s)?$/i);

if(match)
{
  h = (match[1] === undefined) ? 0 : match[1]; // The number of hours
  m = (match[2] === undefined) ? 0 : match[2]; // The number of minutes
}

That will give you the time you want to wait. 这样可以为您提供等待的时间。 You can easily convert it into milliseconds (because its more handy) and update it every seconds for example until it reaches 0. 您可以轻松地将其转换为毫秒(因为它更方便),并且例如每秒钟更新一次,直到达到0。

The setInterval() javascript function allow you to call a function (your update function) every x milliseconds. setInterval() javascript函数允许您每x毫秒调用一个函数(您的更新函数)。 This function returns an identifier that you can store and pass later to the clearInterval() function to clear a timer previously set. 此函数返回一个标识符,您可以存储该标识符,以后将其传递给clearInterval()函数以清除先前设置的计时器。

interval = h * 3600000 + m * 60000; // the interval in ms
stopTime = new Date((new Date()).getTime() + interval); // when to stop counting

counter = setInterval(count, 1000);

Your count function then just has to get the current time, update the interval and check if this one is lower or equal to 0 in order to stop the timer. 然后,您的count功能仅需获取当前时间,更新间隔并检查该时间是否小于或等于0即可停止计时器。

function count()
{
  now      = new Date();
  interval = Math.max(0, stopTime.getTime() - now.getTime());

  if(interval <= 0) clearInterval(counter);
}

Here is an example of such a timer. 这是此类计时器的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM