setInterval() 和setTimeout()
2018-07-31 本文已影响1人
puxiaotaoc
一、setInterval() 方法:
示例:
// 每隔三秒(3000 毫秒)弹出 "Hello"
setInterval(function(){ alert("Hello"); }, 3000);
注意:setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭,由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数;
提示:1000 毫秒= 1 秒;
二、setTimeout()方法:
提示: 如果只想执行一次可以使用 setTimeout() 方法;
<html>
<head>
<script type="text/javascript">
var c=0
var t
function timedCount()
{
document.getElementById('txt').value=c
c=c+1
t=setTimeout("timedCount()",1000)
}
function stopCount()
{
clearTimeout(t)
}
</script>
</head>
<body>
<form>
<input type="button" value="开始计时!" onClick="timedCount()">
<input type="text" id="txt">
<input type="button" value="停止计时!" onClick="stopCount()">
</form>
<p>
请点击上面的“开始计时”按钮。输入框会从 0 开始一直进行计时。点击“停止计时”可停止计时。
</p>
</body>
</html>
计时
三、JS倒计时
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js时分秒毫秒倒计时</title>
</head>
<body>
<div>
<span id="_d">00</span>
<span id="_h">00</span>
<span id="_m">00</span>
<span id="_s">00</span>
<span id="_ms">00</span>
</div>
<script type="text/javascript">
function countTime() {
var date = new Date();
var now = date.getTime();
var endDate = new Date("2018-10-01 00:00:00"); //设置截止时间
var end = endDate.getTime();
var leftTime = end - now; //时间差
var d, h, m, s, ms;
if (leftTime >= 0) {
d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
m = Math.floor(leftTime / 1000 / 60 % 60);
s = Math.floor(leftTime / 1000 % 60);
ms = Math.floor(leftTime % 1000);
if (ms < 100) {
ms = "0" + ms;
}
if (s < 10) {
s = "0" + s;
}
if (m < 10) {
m = "0" + m;
}
if (h < 10) {
h = "0" + h;
}
} else {
console.log('已截止')
}
//将倒计时赋值到div中
document.getElementById("_d").innerHTML = d + "天";
document.getElementById("_h").innerHTML = h + "时";
document.getElementById("_m").innerHTML = m + "分";
document.getElementById("_s").innerHTML = s + "秒";
document.getElementById("_ms").innerHTML = ms + "毫秒";
//递归每秒调用countTime方法,显示动态时间效果
setTimeout(countTime, 50);
}
countTime();
</script>
</body>
</html>
倒计时
参考:https://blog.csdn.net/x550392236/article/details/78033423