当前位置:首页 > JavaScript

用js实现一个倒计时器

2026-04-05 04:31:11JavaScript

实现基础倒计时器

创建一个简单的倒计时器需要设置目标时间,计算剩余时间并更新显示。以下代码展示如何实现从10秒开始的倒计时:

let countdown = 10;
const timerElement = document.getElementById('timer');

function updateTimer() {
  timerElement.textContent = countdown;
  if (countdown <= 0) {
    clearInterval(interval);
    timerElement.textContent = '时间到!';
    return;
  }
  countdown--;
}

const interval = setInterval(updateTimer, 1000);

自定义时长倒计时

允许用户输入自定义倒计时时长:

function startCustomCountdown() {
  const minutes = parseInt(document.getElementById('minutes').value) || 0;
  const seconds = parseInt(document.getElementById('seconds').value) || 0;
  let totalSeconds = minutes * 60 + seconds;

  const interval = setInterval(() => {
    const mins = Math.floor(totalSeconds / 60);
    const secs = totalSeconds % 60;

    document.getElementById('custom-timer').textContent = 
      `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;

    if (totalSeconds <= 0) clearInterval(interval);
    totalSeconds--;
  }, 1000);
}

带暂停/继续功能的倒计时

实现可控制的倒计时器:

let timer;
let remainingTime = 300; // 5分钟
let isRunning = false;

function toggleTimer() {
  if (isRunning) {
    clearInterval(timer);
    isRunning = false;
  } else {
    timer = setInterval(updateDisplay, 1000);
    isRunning = true;
  }
}

function updateDisplay() {
  const minutes = Math.floor(remainingTime / 60);
  const seconds = remainingTime % 60;
  document.getElementById('control-timer').textContent = 
    `${minutes}:${seconds.toString().padStart(2, '0')}`;

  if (remainingTime <= 0) {
    clearInterval(timer);
    return;
  }
  remainingTime--;
}

精确到毫秒的倒计时

使用requestAnimationFrame实现高精度倒计时:

let startTime;
let duration = 5000; // 5秒

function startPreciseCountdown() {
  startTime = performance.now();
  requestAnimationFrame(updatePreciseTimer);
}

function updatePreciseTimer(timestamp) {
  const elapsed = timestamp - startTime;
  const remaining = Math.max(0, duration - elapsed);

  const seconds = (remaining / 1000).toFixed(2);
  document.getElementById('precise-timer').textContent = seconds;

  if (remaining > 0) {
    requestAnimationFrame(updatePreciseTimer);
  }
}

页面不可见时暂停倒计时

使用Page Visibility API优化性能:

用js实现一个倒计时器

document.addEventListener('visibilitychange', () => {
  if (document.hidden) {
    clearInterval(timer);
  } else {
    timer = setInterval(updateTimer, 1000);
  }
});

每个实现方案都针对不同使用场景,基础版本适合简单需求,自定义时长版本提供灵活性,控制版本适合需要交互的场景,高精度版本适用于对时间敏感的应用。根据实际需求选择合适的实现方式。

标签: 计时器js
分享给朋友:

相关文章

jquery.js

jquery.js

jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互等操作。以下是关于 jQuery.js 的核心信息和使用方法: 获取 jQ…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…

js实现二叉树

js实现二叉树

二叉树的基本概念 二叉树是一种树形数据结构,每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树的常见操作包括插入、删除、遍历等。 二叉树的节点定义 在JavaScript中,二叉树的节点可…

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…

js手势实现

js手势实现

手势识别实现方法 在JavaScript中实现手势识别通常涉及监听触摸事件(touchstart、touchmove、touchend)或鼠标事件(mousedown、mousemove、mouseu…

js实现滚动

js实现滚动

实现滚动效果的方法 在JavaScript中实现滚动效果可以通过多种方式完成,以下是一些常见的方法: 使用window.scrollTo() window.scrollTo()方法可以将页面滚动到指…