制作一个倒数计时器,其中时间存储在一个变量中

Make a countdown timer where time stored is in a variable

本文关键字:一个 时间 存储 变量 倒数 计时器      更新时间:2023-09-26

我在JavaScript中有一个变量存储时间。例如,duration是一个以分钟和小时为单位存储时间的变量,如14分钟或1小时20分钟。我如何在JavaScript中使用这个变量制作一个倒计时计时器?

一种方法是使用正则表达式提取所需的值,并使用setInterval()调用函数定期更新计时器。

下面的表达式匹配你的模式:

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

第一个捕获组将为您提供小时数,第二个捕获组为分钟数。您可以通过match方法访问它们。这将返回一个数组,其中包含每个匹配项的匹配项(如果没有找到匹配项,则返回null)。

你可以得到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
}

这样可以给你想等的时间。您可以很容易地将其转换为毫秒(因为它更方便),并每秒钟更新一次,例如,直到它达到0。

setInterval() javascript函数允许你每x毫秒调用一个函数(你的更新函数)。此函数返回一个标识符,您可以存储该标识符并稍后传递给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);

您的count函数然后只需要获得当前时间,更新间隔并检查该间隔是否低于或等于0,以便停止计时器。

function count()
{
  now      = new Date();
  interval = Math.max(0, stopTime.getTime() - now.getTime());
  if(interval <= 0) clearInterval(counter);
}

下面是一个这样的定时器的例子