JavaScript实现动画效果

  说到JavaScript实现动画效果,不得不想到两个函数,setTimeout和setInterval。

   setTimeout的常用的使用方法为 setTimeout(callback, delay),setInterval常用的使用方法为setInterval(callback, delay)

  两者的区别

  

setTimeout(function repeat(){
    /* Some Long block of code... */
    setTimeout(repeat, 10)
}, 10)
setInterval(function(){
    /* Some Long block of code... */
}, 10)

  这两个函数看起来功能似乎是相同的,但实际上并不是。值得注意的是,在setTimeout()的代码中,要在前一个callback回调执行结束并延迟10秒(可能更多但不会更少)以后,才能再执行setTimeout()。而setInterval则是每隔10ms去尝试执行callback回调,而不关注上一个callback是合适执行的。如果setInterval的回调函数还没结束,那么这一次的回调就会被延迟执行到下一次可用的时间点上。如果一直被延迟,到最后,Interval间隔定时器可能会无延期执行。

  下面我使用setTimeout,不设置setTimeout的延迟时间来实现一个动画效果。

  

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
</head>
<body>
        <div >hello!</div>
<script type="text/javascript">
        var timers = {
                timerID : 0,
                timers : [],

                add : function(fn){
                        this.timers.push(fn);
                },

                start: function(){
                        if (this.timerID) return;
                        (function runNext() {
                                if(timers.timers.length > 0){
                                        for (var i = 0; i < timers.timers.length; i++){
                                                if(timers.timers[i]() === false){
                                                        timers.timers.splice(i,1);
                                                }
                                        }
                                        timers.timerID = setTimeout(runNext, 0);
                                }
                        })();
                },
                stop : function(){
                        clearTimeout(this.timerID);
                        this.timerID = 0;
                }
        };

        var box = document.getElementById("box"),x = 0, y = 20;
        timers.add(function(){
                box.style.left = x + "px";
                if ( ++x > 50) return false;
        });

        timers.add(function(){
                box.style.top = y + "px";
                y += 2;
                if (y > 120) return false;
        });

        timers.start();
</script>
</body>
</html>

  学习来自于《JavaScript忍着秘籍》