案例1:每隔2秒钟,切换box的颜色,循环切换
var box = document.querySelector(".box");
//例1: 每隔2秒钟,切换box的颜色,循环切换
//主要逻辑:
colorArry = ["green", "blue", "red"];
//定义索引变量
var Arryindex = 0;
//计时器
setInterval(function () {
Arryindex++;
//不能让索引超过数组的长度 ,超过则需要归0 实现循环
if (Arryindex > colorArry.length - 1) {
Arryindex = 0;
}
box.className = "box " + colorArry[Arryindex];
}
, 1000); (0);
案例2:通过控制style改变标签样式: 把一个矩形1秒后变为圆形
var box2 = document.querySelector(".box2");
//用style 标签样式修改标签形式
box2.style.width = "100px";
box2.style.height = "100px";
box2.style.border = "1px solid black"
setTimeout(function () {
box2.style.borderRadius = "50%";
}, 1000);
setInterval 与 setTimeout 的区别: setTimeout 只执行一次函数,setInterval 间隔一段时间就执行,可以执行多次
setTimeout() 方法用于在指定的毫秒数后调用函数或计算表达式,而setInterval()则可以在每隔指定的毫秒数循环调用函数或表达式,直到clearInterval把它清除。