定時(shí)器

setTimeout 只執(zhí)行一次的定時(shí)器
clearTimeout 關(guān)閉只執(zhí)行一次的定時(shí)器
setInterval 反復(fù)執(zhí)行的定時(shí)器
clearInterval 關(guān)閉反復(fù)執(zhí)行的定時(shí)器

定時(shí)器的基本用法

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>定時(shí)器的基本用法</title>
<style type="text/css">

</style>
<script type="text/javascript">
    //單次定時(shí)器
    var timer = setTimeout(function(){
        alert('hello!');
    }, 3000);

    //清除單次定時(shí)器
    clearTimeout(timer);

    //反復(fù)循環(huán)定時(shí)器
    var timer2 = setInterval(function(){
        alert('hi~~~');
    }, 2000);

    //清除反復(fù)循環(huán)定時(shí)器
    clearInterval(timer2);
</script>

</head>
<body>

</body>
</html>

定時(shí)器動(dòng)畫

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>定時(shí)器動(dòng)畫</title>
<style type="text/css">
.box{
width: 100px;
height: 100px;
background-color: gold;
position: fixed;
left: 20px;
top: 20px;
}
</style>
<script type="text/javascript">
window.onload = function(){
var oBox = document.getElementById('box');

        var left = 20;
        //反復(fù)循環(huán)定時(shí)器,每30毫秒修改一次盒子的left值
        var timer = setInterval(function(){
            left += 2;
            oBox.style.left = left + 'px';

            //當(dāng)left值大于700時(shí)停止動(dòng)畫(清除定時(shí)器)
            if(left > 700){
                clearInterval(timer);
            }
        },30);
    }
</script>

</head>
<body>
<div class="box" id="box"></div>
</body>
</html>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容