I. Usage of settimeout and setinterval (http://www.css88.com/archives/5804)
SetTimeout is a timeout call, and JavaScript is a single-threaded parser, so only a piece of code can be executed within a certain amount of time; the second parameter of SetTimeout just tells JavaScript how long to add the current task to the execution queue, and if the queue is empty, The code that is currently added executes immediately, and if the queue is not empty, it will wait until the previous code has finished executing. (So the method in the timeout call does not have to be executed immediately after the given time-out, and the preceding code is likely to execute longer than the given timeout time)
The timeout call is executed only once per call, and the SetTimeout method is added inside the settimeout function to repeatedly execute the timeout call.
SetTimeout (function () {var div = document.getElementById ("Div4");//var left = parseint (div.style.left) + 5;var left = d Iv.offsetleft + 5;div.style.left = left + ' px ', if (left < $) {SetTimeout (Arguments.callee, 50);}}, 50);
SetInterval is an intermittent call that is invoked once until the page is unloaded. As with settimeout, the specified time interval represents when the code for the timer is added to the queue, and setinterval ensures that the timer code rules are inserted into the queue, but if the code before the timer code executes longer than the timer interval, the following occurs: 1, Some intervals may be skipped, and the interval between 2, the code execution of multiple timers may be smaller than expected.
var num = 0;var max = 10;var intervalid = null;function incrementnumber () {num + +; if (num = = max) {Clearinterval (Inter valId);}} Intervalid = SetInterval (Incrementnumber, 500);
Therefore, the SetTimeout method is generally used to implement a timer (such as the first instance).
var num = 0;var max = 10;//var intervalid = null;function incrementnumber () {num + +; if (num < max) {SetTimeout (incr Ementnumber, 1000); Console.log ("1");}} SetTimeout (incrementnumber,1000);
SetTimeout () and SetInterval ()