javascript计时器

一、计时器:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>0</h1>
<h2>10</h2>
<script>

	/**

    let count = 0;
    //1.开启定时器  每隔1000毫秒=1秒  调用一次fn方法
    //当方法作为参数进行传递时不需要加()  只有调用方法时带()

    let timer = setInterval(fn,1000);
    function fn() {
        count++;
        let h1 = document.querySelector("h1");
        h1.innerText=count;
        //第五次停止定时器
        if (count==5){
            clearInterval(timer);
        }
    }*/


	let num=0;
    //2.匿名方法开启定时器
    setInterval(function () {
		num++;
        let h2 = document.querySelector("h2");
        h2.innerText=num;
    },1000);

    //3.开启只执行一次的定时器
    setTimeout(function () {
        alert("时间到!");
    },3000);


</script>
</body>
</html>

二、电子时钟案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>

        let num=0;
        //匿名方法开启定时器
        setInterval(function () {
            //var date = new Date(time);
            var date = new Date();
            var year = date.getFullYear(),
                month = date.getMonth() + 1,//月份是从0开始的
                day = date.getDate(),
                hour = date.getHours(),
                min = date.getMinutes(),
                seconds=date.getSeconds();
            console.log(year+"-"+month+"-"+day+" "+hour+":"+min+":"+seconds);
            let h2 = document.querySelector("h2");
            h2.innerText=year+"-"+month+"-"+day+" "+hour+":"+min+":"+seconds;
        },1000);
    </script>
</head>
<body>
    <h2>时间:</h2>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/gulanga5/article/details/124432313