一、setInterval() 方法
语法结构:
setInterval("调用的函数", "指定的时间间隔") 交互时间
setInterval ( function,time)
function:必需。要调用的函数或要执行的代码串
time:交互时间:周期执行或调用表达式之间的时间间隔,以毫秒计(1s=1000ms)
举个栗子:
每三秒(3000 毫秒)弹出 "Hello" :
setInterval(function() {
alert("Hello");
}, 3000);
注意:
- setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。
- 1000 毫秒= 1 秒。
如果只执行一次可以使用 setTimeout() 方法。
举个栗子:
显示当前时间( setInterval() 方法会每秒执行一次函数
var myVar = setInterval(function() {
myTimer()
}, 1000);
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
</script>
</head>
<body>
<div id="demo"></div>
</body>
二、Window clearInterval() 方法
clearInterval() 方法可取消由 setInterval() 函数设定的定时执行操作。
clearInterval() 方法的参数必须是由 setInterval() 返回的 ID 值。
注意: 要使用 clearInterval() 方法, 在创建执行定时操作时要使用全局变量:
举个栗子:
使用 clearInterval() 来停止 setInterval 的执行:
var timer = 0; //定义一个变量,用于计时
var myVar = setInterval(function() { //每秒执行一次函数
myTimer() //调用函数//设置时间记录
timer ++; //计时器自增
console.log(timer) //输出计时器
if (timer >= 5) { //计时器大于5时,调用函数
clearInterval(myVar) //清除计时器
}
},
1000);
function myTimer() { //函数
var d = new Date(); //创建日期对象
var t = d.toLocaleTimeString(); //获取时间
document.getElementById("demo").innerHTML = t; //输出时间
}
function mystopFunction() { //停止函数
console.log("停止")
clearInterval(myVar);
} //清除定时器
三、Window setTimeout() 方法 时间戳
语法结构:
setTimeout(“调用的函数”, “指定的时间后") 延迟时间
参数说明: 1.代码:要调用的函数或要执行的代码串
2.延迟时间:在执行代码前需要等待的时间,以毫秒为单位(1s=1000ms) 返回值: 一个可以传递给clearInterval()从而取消对“代码”的周期性执行的值
3. 使用 clearTimeout() 方法来阻止函数的执行。
栗子:
3 秒(3000 毫秒)后弹出 "Hello" :
setTimeout(function() {
alert("Hello");
}, 3000);
四、Window clearTimeout() 方法
clearTimeout() 方法可取消由 setTimeout() 方法设置的定时操作。
clearTimeout() 方法的参数必须是由 setTimeout() 返回的 ID 值。
注意: 要使用 clearTimeout() 方法, 在创建执行定时操作时要使用全局变量:
举个栗子:
点击 "开始计数!" 按钮开始执行计数程序。点击 "停止计数!" 按钮停止后,可以再次点击点击 "开始计数!" 按钮会重新开始计数。
<body>
<button onclick="startCount()">开始计数!</button> <input type="text" id="txt">
<button onclick="stopCount()">停止计数!</button>
</body>
<script type="text/javascript">
var c = 0;
var t;
var timer = 0;
function timedCount() {
document.getElementById("txt").value = c;
c = c + 1;
t = setTimeout(function() {
timedCount()
}, 1000);
}
function startCount() {
if (!timer) {
timer = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer = 0;
}
</script>