计时器 详细介绍

喜欢前端的第一天

以前不怎么喜欢前端,从今天开始对此有了一定深入的了解之后,便慢慢的开始由心而发的一种喜欢。

定时器是什么

定时器的具体方法由Window对象提供,共有以下两种定时器:

  • 延迟执行:指的是指定程序代码在指定时间后被执行,而不是立即被执行。
  • 周期执行:指的是指定程序代码在指定时间为间隔,重复被执行。

目前,HTML页面中多数动态效果,以及动画效果等均由定时器内容完成。

延迟执行

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>延迟执行</title>
</head>
<body>
<script>
    console.log( 'this is message...' );
    var t=setTimeout( function(){
    console.log( 'this is timeout...' );
    },10000);
    //clearTimeout(t);
    console.log('this is message too.. .' );
</script>

</body>
</html>

setTimeout ( function,delay)方法

作用:

  • 设置一个定时器

参数

  • function -表示延迟执行的代码逻辑
  • delay -表示延迟执行的时间,单位为毫秒

返回值

  • 表示当前定时器的标识

注意:
setTimeout 会打乱代码默认的顺序执行流程

周期执行

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>周期执行</title>
</head>
<body>
<script>
    console.log('this is message...' );
    /*setInterval( function(){
    console.log('this is interval...' );
        },1000);*/
    // function fun(){
    // console.log('this is interval...');
    // setTimeout(fun , 1000);
    // }
    // fun();
    (function fun( ){
    console.log('this is interval...' );
    setTimeout( fun,1000);
    // setTimeout( arguments.callee,1000);
    })();
    console.log('this is message too...' );
</script>
</body>
</html>

setInterval ( function,delay)方法

  • 作用
    设置一个周期执行的定时器

参数

  • function-表示延迟执行的代码逻辑
  • delay -表示延迟执行的时间,单位为毫秒

返回值

  • 表示当前定时器的标识

案例:

HTML5的动画方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HTML5的动画方法</title>
</head>
<body>
<script>
    console.log('this is message...');
    var requestAnimationFrame = webkitRequestAnimationFrame || mozRequestAnimationFrame
    requestAnimationFrame (function(){
    	console.log('this is animation...')
    });
    requestAnimationFrame();
    console.log('this is message too...');
</script>
</body>
</html>

requestAnimationFrame (callback)方法(类似于延迟执行)

作用

  • HTML5新增的动画方法

参数

  • callback - 表示执行动画逻辑的回调函数

返回值

  • 表示当前执行动画的标识

注意 - requestAnimationFrame 具有浏览器兼容问题

cancelAnimationFrame ( animationID)方法

作用

  • 取消由requestAnimationFrame ()方法设定的动画机制

方块自动移动

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>方块自动移动</title>
    <style>
        body {
        	margin: 0;
        }
        #box {
	        width: 50px;
	        height: 50px;
	        background-color: lightcoral;
	        position: absolute;
	        top: 300px;
	        left: 100px;
        }
    </style>
</head>
<body>
<div id="box"></div>
<script>
    var box = document.getElementById ( 'box' ) ;
    box.addEventListener( 'click' , isMove) ;
    //定义一个标识–表示是停止还是移动
    var flag = false;//表示停止
    var t;
    function isMove() {
        if (!flag) {//如果停止,就移动
            //将标识设置为true - 表示移动
            flag = true;
            move();
        } else {//如果移动,就停止
            flag = false;
            stop();
        }
    }
    function move() {
        //1.获取当前方块的left样式属性值
        var style = window.getComputedStyle(box);
        var left = parseInt(style.left);
        //2.增加left样式属性值
        left++;
        //3.利用内联样式覆盖外联样式
        box.style.left = left + 'px';
        //4.设置定时器
        t = setTimeout(move, 5);
    }
    //实现方块停止逻辑
    function stop(){
    	clearTimeout(t);
    }
</script>
</body>
</html>

小球垂直移动

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>小球垂直移动</title>
    <style>
        body {
        	margin: 0;
        }
        .box {
	        width: 50px;
	        height:50px;
	        background-color: lightcoral;
	        border-radius: 25px;
            position: absolute;
            left: 400px;
            top: -50px;
        }
    </style>
</head>
<body>
<!--<div id="box"></div>-->
<script>
    //var box = document.getElementById ( 'box' );
    var body=document.body;
    const WIDTH = window.innerWidth;
    //向页面中创建小球
    function createBox(){
	    var div = document.createElement( 'div') ;
	    div.setAttribute( 'class' , 'box' );
	        var random = Math.random() *(WIDTH-50);
	        div.style.left = random + 'px' ;
	        body .appendChild(div);
    }
    //控制小球向下移动
    function moveDown(){
        var boxs = document.getElementsByClassName ( 'box');
        for (var i=0; i<boxs.length;i++) {
            var box = boxs[i];
            var style = window.getComputedStyle(box);
            var boxTop = parseInt(style.top);
            boxTop += 10;
            box.style.top = boxTop + 'px';
        }
    }
    //createBox();/创建多个小球
    //创建多个小球
    for (var i=0; i<10; i++){
    	createBox();//创建一个小球
    }
    setInterval ( function() {
        moveDown();
    },500);
</script>
</body>
</html>

高度值变化动画

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>高度值变化动画</title>
    <style>
        body {
        	margin: 0;
        }
        #menu {
	        width: 100px;
	        height: 300px;
	        border: 1px solid black;
            position: absolute;
            left: 400px;
            top: 100px;
        }
    </style>
</head>
<body>
<div id="menu"></div>
<script>
    //1.获取指定元素
    var menu = document.getElementById ( 'menu' );
    //函数–实现指定元素的高度值减少
    function slideUp(){

    //2.获取指定元素的当前有效样式
    var style = window.getComputedStyle(menu);
        //3.获取指定元素的高度值
    var height=parseInt(style.height);
        //判断当前的高度值是否为o
    if (height <= 0) {
		//将指定元素进行隐藏
        menu.style.display = 'none' ;
        clearTimeout(t)
    } else {
	    //4.减少指定元素的高度值
	    height--;
	    //5.将减少的高度值重新为指定元素进行设置
	    menu.style.height = height + 'px';
	    //6.设置定时器
	    var t = setTimeout(slideUp,5);
    }
}
        slideUp();
</script>

</body>
</html>

键盘控制方块方向

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>键盘控制方块移动</title>
    <style>
        body {
            margin: 0;
        }
        #box {
            width: 50px;
            height: 50px;
            background-color: coral;
            position: absolute;
            left: 50px;
            top: 50px;
        }
    </style>
</head>
<body>
    <div id="box"></div>
    <script>
        var body = document.body;
        var html = document.documentElement;
        // 获取box的div
        var box = document.getElementById ('box');
        // getComputedStyle() - 指定元素的有效样式
        var boxStyle = window.getComputedStyle(box);
        var boxTop = parseInt(boxStyle.top);
        var boxLeft = parseInt (boxStyle.left);
        // 用于键盘控制方块
        var tUp,tDown,tLeft,tRight;
        body.addEventListener('keydown',function(event){
            var key = event.code;
            console.log(key);
            // 每次键盘事件触发时,重新获取当前的top和left值
            boxTop = parseInt(boxStyle.top);
            boxLeft = parseInt (boxStyle.left);
            switch (key) {
                case 'ArrowUp':
                    moveUp();
                    break;
                case 'ArrowDown' :    
                    moveDown();
                    break;
                case 'ArrowLeft':
                    moveLeft();
                    break;
                case 'ArrowRight':
                    moveRight();
                    break;
                case 'Space':
                    if (tUp !== undefined) {
                        clearTimeout(tUp);
                    }
                    if (tDown !== undefined) {
                        clearTimeout(tDown);
                    }
                    if (tLeft !== undefined) {
                        clearTimeout(tLeft);
                    }
                    if (tRight !== undefined) {
                        clearTimeout(tRight);
                    }
                    break;
            }
        });
        function moveUp(){
            // 先自减 , 再赋值
            box.style.top = (--boxTop) + 'px';
            tUp = setTimeout(moveUp,5);
            if (tDown !== undefined) {
                clearTimeout(tDown);
            }
            if (tLeft !== undefined) {
                clearTimeout(tLeft);
            }
            if (tRight !== undefined) {
                clearTimeout(tRight);
            }
        }

        function moveDown(){
            box.style.top = (++boxTop) + 'px';
            tDown = setTimeout(moveDown,5);
            if (tUp !== undefined) {
                clearTimeout(tUp);
            }
            if (tLeft !== undefined) {
                clearTimeout(tLeft);
            }
            if (tRight !== undefined) {
                clearTimeout(tRight);
            }
        }

        function moveLeft(){
            box.style.left = (--boxLeft) + 'px';
            tLeft = setTimeout(moveLeft,5);
            if (tUp !== undefined) {
                clearTimeout(tUp);
            }
            if (tDown !== undefined) {
                clearTimeout(tDown);
            }
            if (tRight !== undefined) {
                clearTimeout(tRight);
            }
        }

        function moveRight(){
            box.style.left = (++boxLeft) + 'px';
            tRight = setTimeout(moveRight,5);
            if (tUp !== undefined) {
                clearTimeout(tUp);
            }
            if (tDown !== undefined) {
                clearTimeout(tDown);
            }
            if (tLeft !== undefined) {
                clearTimeout(tLeft);
            }
        }
    </script>
</body>
</html>

今日心情

今日心情

人得学会竭尽全力,但也得接受无能无力。
努力赚钱,努力做到内心强大,努力使自己变得优秀,那些不相干的人,你们算哪块小饼干。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bliss小宝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值