先介绍一对函数setinterval(函数,毫秒数)—>就是周期性的调用函数 和clearinterval(函数名)—>停止调用
具体应用计时器
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>定时器</title>
<script>
function showTime(){
var time=new Date();
var y=time.getFullYear();
var mon =time.getMonth();
var d=time.getDate();
var h=time.getHours();
var m=time.getMinutes();
var s=time.getSeconds();
document.getElementById("today").innerHTML=y+"年"+mon+"月"+d+"日"+h+":"+m+":"+s;
}
var flag1=setInterval("showTime()",1000);
</script>
</head>
<body>
<div id="today">
显示时间------------
<br />
</div>
<a href="javascript:window.clearInterval(flag1)"> 停止计算器</a>
</body>
</html>
这是点名器效果
这是点名器代码
*{
margin: 0;
padding: 0;
}//清除网页默认的内外边距
h1{
text-align: center;
margin: 100px auto;
}
#new1{
width: 400px;
height: 200px;
margin: 100px auto;
padding: 50px;
background: orange;
border-radius: 50px;//让四个角变圆
}//设置好大小和内外边距
#new2{
width: 300px;
height: 90px;
margin: 50px auto;
border-radius:10px;
box-sizing: 300px;
background: gray;
}
#new3{
width: 100px;
height: 26px;
border-radius:5px;
margin: auto;
background: green;
padding: 8px;
}
a{
text-decoration: none;
color: black;
}//清除a标签的下划线和修改颜色
.text{
font-size: 30px;
text-align: center;
line-height: 100px;
}//让姓名居中
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>点名器</title>
<link href="css/my.css" type="text/css" rel="stylesheet"/>
</head>
<body>
<h1>随机点名器</h1>
<div id="new1">
<div id="new2">
<p id="displayNames" class="text"> 姓名</p>
</div>
<div id="new3">
<a id="w" href="#" onclick="start()" >开始</a>
</div>
</div>
</body>
</html>
<script>
var count=0;//开始结束的标记
var time;
var names=["张三","李四","王二麻子","小龙女","李小龙","八岐大蛇","宙斯","哈迪斯","暗月猎手","玉兔","嫦娥","孙悟空","司马懿"];
function start(){
var start=document.getElementById("w");
var color=document.getElementById("new3");
var displayBoard=document.getElementById("displayBoard");
if(count%2+1==1){//通过判断单击次数判断开始还是结束
start.innerHTML="停止";
color.style.background="red";
count++;
time = setInterval(function(){
var name=randomName();
console.log(name);
//轮放名字
displayNames.innerHTML=name;
}, 100);
}else{
start.innerHTML="开始";
color.style.background="green";
count++;
clearInterval(time);
}
}
function randomName(){
var randomNum=Math.ceil(Math.random()*100)%names.length+1;//在全部名字里面选择
return names[randomNum];
}
</script>