0.码仙励志
过去的事,交给岁月去处理;将来的事,留给时间去证明。我们真正要做的,就是牢牢地抓住今天,让今天的自己胜过昨天的自己
1.setTimeout
setTimeout(函数,时间);//定时器,只执行一次函数的代码-----一次性的定时器,返回值是定时器的id
clearTimeout(定时器的id);//清理定时器
<body>
<input type="button" value="开始" id="btn1">
<input type="button" value="停止" id="btn2">
<script>
var timeId;
document.getElementById("btn1").onclick = function () {
function f1() {
console.log("定时器执行了");
};
//会在5秒后执行,只执行一次
timeId = setTimeout(f1, 5000);
};
document.getElementById("btn2").onclick = function () {
//如果在5秒之内点击,定时器直接被清理,不会执行
clearTimeout(timeId);
console.log("定时器被清理了");
};
</script>
</body>
2.setInterval
setInterval(函数,时间);//定时器,隔一段时间就执行一次函数的代码,返回值是定时器的id
clearInterval(定时器的id);//清理定时器
<body>
<input type="button" value="开始" id="btn1">
<input type="button" value="停止" id="btn2">
<script>
var timeId;
document.getElementById("btn1").onclick = function () {
function f1() {
console.log("定时器执行了");
};
//会在5秒后执行,每5秒执行一次
timeId = setInterval(f1, 5000);
};
document.getElementById("btn2").onclick = function () {
//如果点击,定时器直接被清理,不会继续执行
clearInterval(timeId);
console.log("定时器被清理了");
};
</script>
</body>