JavaScript: 计时操作
1 周期性定时器 setInterval
setInterval(1,2):周期性触发代码exp (常用)
1:执行语句
2:时间周期,单位为毫秒
案例:闪烁的字体 (1秒1变色)
<body> <h1 id="title">拉勾网:极速入职</h1> <script> var colors = ["red","blue","yellow","pink","orange","black"]; var i = 0; function bian(){ document.getElementById("title").style.color = colors[i++]; if(i == colors.length){ i = 0; // 颜色重新开始 } } setInterval(bian,100); // 每隔0.1秒,执行一次bian函数 </script> </body>
案例:在闪烁字体的基础上扩展,闪烁的电子时钟
<body> <h1 id="title"></h1> <script> var colors = ["red","blue","yellow","pink","orange","black"]; var i = 0; function bian(){ document.getElementById("title").style.color = colors[i++]; if(i == colors.length){ i = 0; // 颜色重新开始 } } function time(){ var d = new Date(); var str = d.getFullYear()+"年"+(d.getMonth()+1)+"月"+d.getDate()+"号 "+d.getHours()+"点"+d.getMinutes()+"分"+d.getSeconds()+"秒"; document.getElementById("title").innerHTML = str; } setInterval(bian,100); // 每隔1秒,执行一次变色函数bian setInterval(time,100); // 每隔1秒,执行一次时间函数time </script> </body>
2 停止定时器 clearInterval
案例:模拟年会抽奖
<body> <img id="tu" src="../lagou-html/img/1.jpg" width="50%" /> <br /> <button onclick="begin()">开始</button> <button onclick="stop()">停止</button> <script> var arr = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"]; function begin() { timer = setInterval(bian, 100); // 没有使用var,所以timer是全局变量 } function stop() { clearInterval(timer); // 停止定时器 } function bian() { var i = Math.floor(Math.random() * arr.length); // 0-4 document.getElementById("tu").src = "../lagou-html/img/" + arr[i]; } </script> </body>
3 一次性定时器 setTimeout
相当于延迟的效果,只执行一次
<script> function bian(){ document.body.style.backgroundColor = "red"; } //3秒之后调用 setTimeout(bian,3000); </script>