Summary Advanced Timer

Summary Advanced timer
before the summary should be noted that two questions:

  1. setInterval () is a predetermined interval timer, perform many times.
  2. setTimeout () is a delay in accordance with a predetermined interval, is performed only once.

Timers are used in a specified interval is added to the queue, and not immediately after a specified interval.
Repeat Timer
use setInterval () to create a timer to ensure that the rules of the code is inserted into the timer queue. The problem with this approach is that:

  • Timer code may be added to the queue before the code again to execute the code has not been completed. Led timer continuously performed several times, in the middle without any pause.

Fortunately, JavaScript smart enough to avoid this problem.
When using the setInterval (), only when the timer is not any other instances, it will be added to the queue timer codes. This ensures that the timer queue is added to the minimum time interval is a specified interval.

This repetition timer has two problems:

  1. Some interval will be skipped.
  2. Code executes multiple timer interval may be less than expected.

To avoid setInterval () of the two timers disadvantages exist, the following mode can be used with the call chain.

setTimeout(function(){
	setTimeout(arguments.callee,200);
},200)
<!doctype html>
<html>

    <head>
        <title></title>
    </head>

    <body>
        <div id="myDiv" style="position:absolute;width:100px;height:100px;left:0px;top:10px;background:red;"></div>

        <script type="text/javascript">
            setTimeout(function() {
                var div = document.getElementById("myDiv"),
                    left = parseInt(div.style.left)+5;
                    //console.log(left);
                div.style.left = left + "px";
                if (left < 200) {
                    setTimeout(arguments.callee, 50);
                }
            }, 50);
        </script>
    </body>

</html>

Guess you like

Origin blog.csdn.net/boysky0015/article/details/94394642