如何用js实现定时器?

2025-10-04 16:22:42

1、首先,设计html页面。先看body部分。设计时分秒在li中

<body>

<div class="wrap">

<ul>

<li>00</li>

<li>00</li>

<li>00</li>

</ul>

</div>

</body>

如何用js实现定时器?

2、再看样式部分:用after给li加一个:这样做方便对li中的内容操作。

<style>

.wrap{

box-sizing: border-box;

width: 400px;

height: 300px;

margin:100px auto;

border:10px inset #2b1f1f;

font-size :16px;

color:blueviolet;

}

.wrap ul li {

width: 100px;

height: 100px;

float:left;

text-align: center;

padding-top:30px;

margin:30px auto;

list-style: none;

font-size:20px;

list-style: none;

}

.wrap ul li:nth-child(1){

background-color: pink;

}

.wrap ul li:nth-child(2){

background-color: orange;

}

.wrap ul li:nth-child(3){

background-color:rgb(231, 24, 180);

}

.wrap ul li:nth-child(1)::after{

content:":";

}

.wrap ul li:nth-child(2)::after{

content:":";

}

</style>

如何用js实现定时器?

如何用js实现定时器?

3、然后是js定义对象,存储时分秒。这里为了可以实现时分秒的加法,将其转换为number类型。

let ali=document.querySelectorAll(".wrap ul li");

let hh=Number(ali[0].innerHTML);

let mm=Number(ali[1].innerHTML);

let ss=Number(ali[2].innerHTML);

如何用js实现定时器?

4、然后设置setInterval定时。由于时分秒是60进制,所以到60时需要置0。为了更加符合实际,当时分秒<10时,将其前面加0。

let one=setInterval(function(){

ss=(ss%60)+1;

if(ss==60){

ss=0;

mm=(mm%60)+1;

if(mm==60){

mm=0;

hh=(hh%60)+1;

}

}

//add [0,.....9] to 0

ali[0].innerHTML=hh<10?"0"+hh:hh;

ali[1].innerHTML=mm<10?"0"+mm:mm;

ali[2].innerHTML=ss<10?"0"+ss:ss;

 

//取消计时器

if(hh==2){

clearInterval(one);

}

else{

console.log('不取消');

}

},500);

如何用js实现定时器?

5、最后就可以看见时间一直在滴答滴答的走啊

如何用js实现定时器?

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢