用Javascript制作倒数计秒器

博客介绍了使用JavaScript实现倒计时功能的方法。通过创建HTML文件,添加倒计时显示元素和开始、停止按钮,编写JavaScript代码实现倒计时逻辑。代码中定义了起始时间、结束时间和时间间隔,在onTimer函数中处理时间递减,还可调整时间间隔使倒计时更精确。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

00:00:11:00

新建一个文本文件(后缀名是TXT),然后将下面的源代码全部复制/粘贴到这个文本文件中,保存后改变这个文本文件的后缀名为HTML,然后在IE浏览器中打开并运行。

 

<span id="clock">00:00:11:00</span>
<input type=button value="start countdown!" onclick="onTimer()">
<input type=button value="stop countdown!" onclick="window.clearTimeout(timer);">
<script language="Javascript">
/* This notice must be untouched at all times.

countdown.js    v. 1.0
The latest version is available at
http://blog.csdn.net/yjgx007

Copyright (c) 2004 Xinyi.Chen. All rights reserved.
Created 7/30/2004 by Xinyi.Chen.
Web: http://blog.csdn.net/yjgx007
E-Mail: chenxinyi1978@hotmail.com
Last modified: 7/30/2004

This program is free software;
you can redistribute it and/or modify it under the terms of the
GNU General Public License as published by the Free Software Foundation;

See the GNU General Public License
at http://www.gnu.org/copyleft/gpl.html for more details.
*/
var elapse = 100;
var start = document.all("clock").innerText;
var finish = "00:00:00:00";
var timer = null;
function onTimer(i)
{

if (start == finish)
{
  window.clearTimeout(timer);
  alert("time is reach!");
  return;
}

var hms = new String(start).split(":");
var ms = new Number(hms[3]);
var s = new Number(hms[2]);
var m = new Number(hms[1]);
var h = new Number(hms[0]);
 
ms -= 10;
if (ms < 0)
{
  ms = 90;
  s -= 1;
  if (s < 0)
  {
    s = 59;
    m -= 1;
  }
 
  if (m < 0)
  {
    m = 59;
    h -= 1;
  }
}

var ms = ms < 10 ? ("0" + ms) : ms;
var ss = s < 10 ? ("0" + s) : s;
var sm = m < 10 ? ("0" + m) : m;
var sh = h < 10 ? ("0" + h) : h;

start = sh + ":" + sm + ":" + ss + ":" + ms;
document.all("clock").innerText = start;

timer = window.setTimeout("onTimer()",elapse);
}
</script>

考虑到onTimer函数中执行语句的延迟,实际中你可以减少elapse的值,使得倒计数秒更为精确!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值