用Javascript制作倒数计秒器

来源:互联网 发布:天启软件世界 编辑:程序博客网 时间:2024/05/06 20:33

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的值,使得倒计数秒更为精确!

原创粉丝点击