BOM series The first timer settimeout and Setinterval_javascript tips

Source: Internet
Author: User
Tags setinterval time interval

SetTimeout ()

The settimeout () method is used to specify that a function or string is executed after a specified number of milliseconds. It returns an integer that represents the number of the timer, which can be passed to Cleartimeout () to cancel the execution of this function

In the following code, the console first outputs 0, probably over 1000ms or 1s, the output timer settimeout () method returns a value of 1

var Timer = settimeout (function () {
console.log (Timer);
},1000);
Console.log (0);

Can also be written as a string parameter, because this form will cause JavaScript engine two resolution, reduce performance, it is not recommended to use

var Timer = settimeout (' Console.log (Timer); ', 1000);
Console.log (0);

If the second argument of SetTimeout is omitted, the parameter defaults to 0

In the following code, the console appears 0 and 1, but 0 is in front, explaining the question

var Timer = settimeout (function () {
console.log (Timer);
});
Console.log (0);

In fact, in addition to the first two parameters, the SetTimeout () method also allows you to add more parameters that will be passed into the function in the timer

In the following code, the console is about 1000ms or 1s, output 2, while the ie9-browser only allows settimeout to have two parameters, does not support more parameters, will output Nan in the console

settimeout (function (a,b) {
console.log (a+b);
},1000,1,1);

You can use Iife parameters to be compatible with the Ie9-browser's function arguments

SetTimeout ((function (a,b) {return
function () {
console.log (a+b);
}
}) (1,1), 1000);

or write the function out of the timer, then the function is called with the parameter in the anonymous function in the timer.

function test (a,b) {
console.log (a+b);
}
settimeout (function () {
test (1,1);
},1000);

This points to

The This mechanism series has detailed the 4 binding rules that this point to, because there is an implicit loss of this in the timer and it is extremely easy to make an error, so here's another explanation

var a = 0;
function foo () {
console.log (THIS.A);
};
var obj = {
a:2,
foo:foo
}
settimeout (obj.foo,100);//0
//equivalent to
var a = 0;
settimeout (function foo () {
console.log (THIS.A);
},100);//0

To get a property value in the Obj object, you can implicitly bind the Obj.foo function in an anonymous function in the timer

var a = 0;
function foo () {
console.log (THIS.A);
};
var obj = {
a:2,
foo:foo
}
settimeout (function () {
obj.foo ();
},100);//2

Alternatively, you can use the Bind method to bind this to the Foo () method to obj

var a = 0;
function foo () {
console.log (THIS.A);
};
var obj = {
a:2,
foo:foo
}
settimeout (Obj.foo.bind (obj), 100);//2

Cleartimeout ()

The settimeout function returns an integer value that represents the counter number, passes the integer to the Cleartimeout function, and cancels the corresponding timer

After 100ms, the console outputs the return value of the SetTimeout () Method 1
var Timer = settimeout (function () {
console.log (Timer);
},100);

So you can use this value to cancel the corresponding timer.

var Timer = settimeout (function () {
console.log (Timer);
},100);
Cleartimeout (Timer);

Or use the return value directly as a parameter

var Timer = settimeout (function () {
console.log (Timer);
},100);
Cleartimeout (1);

In general, the integer value returned by the settimeout is continuous, that is, the second SetTimeout method returns a number of integers 1 greater than the first integer value

Console output 1, 2, 3
var Timer1 = settimeout (function () {
console.log (Timer1);
},100);
var Timer2 = settimeout (function () {
console.log (Timer2);
},100);
var Timer3 = settimeout (function () {
console.log (Timer3);
},100);

SetInterval ()

The use of setinterval is exactly the same as settimeout, except that the setinterval specifies that a task is executed every once in a while, that is, an infinite number of times.

<button id= "btn" >0</button>
<script>
var timer = setinterval (function () {
btn.innerhtml = Number (btn.innerhtml) + 1;
},1000);
Btn.onclick = function () {
clearinterval (timer);
btn.innerhtml = 0;
}
</script>

Attention The HTML5 standard stipulates that the shortest time interval for settimeout is 4 milliseconds; the setinterval minimum interval is 10 milliseconds, that is, the interval less than 10 milliseconds is adjusted to 10 milliseconds

Most computer monitors have a refresh rate of 60HZ, which is roughly equivalent to redrawing 60 times per second. Therefore, the optimal cycle interval for the smoothest animation effect is 1000MS/60, which is approximately equal to 16.6ms

To save electricity, the browser expands the time interval to 1000 milliseconds for those pages that are not in the current window. In addition, if the laptop is in a battery-powered state, chrome and IE 9 versions will switch the time interval to the system timer, about 16.6 milliseconds

Operating mechanism

To explain the remaining questions in the previous section, why is 0 of the console results of the following code appearing ahead of 1?

settimeout (function () {
console.log (1);
});
Console.log (0);

In fact, setting the second parameter of settimeout to 0s does not mean immediately executing the function, but putting the function into the code queue

In the following example, an event handler is set for a button btn. The event handler sets a timer that is called after a 250ms. When you click the button, the OnClick event handler is first added to the queue. After the program is executed, the timer is set, and after 250ms, the specified code is added to the queue for execution.

Btn.onclick = function () {
settimeout (function () {
console.log (1);
},250);
}

If the OnClick event handler in the above code executes 300MS, the timer's code will be executed at least after 300ms after the timer has been set. All the code in the queue waits until the JavaScript process is idle, regardless of how they are added to the queue

As shown in the figure, although the timer code has been added at 255MS, it cannot be performed at this time because the OnClick event handler is still running. The first time the timer code can be executed is at 300ms, after the onclick event handler is finished

The problem of SetInterval

The problem with setinterval () is that the timer code may not have been executed until the code was added to the queue again, resulting in the timer code running several times without any pauses. The JavaScript engine solves this problem by adding the timer code to the queue only if there is no other code instance for the timer when using SetInterval (). This ensures that the minimum time interval that the timer code adds to the queue is the specified interval

However, this can cause two problems: 1, some intervals are skipped, 2, the interval between code execution for multiple timers may be smaller than expected

Suppose that an OnClick event handler uses Serinterval () to set a timer of 200ms intervals. If the event handler takes more than 300ms of time to complete, and the timer code takes about the same amount of time, it also appears to skip an interval

The first timer in the example is added to the queue at 205ms, but it cannot be performed until 300ms. When the timer code is executed, another copy is added to the queue at 405ms. At the next interval, at 605MS, the first timer code is still running, and there is already an instance of the timer code in the queue. As a result, the timer code at this point in time will not be added to the queue

Iterative settimeout

To avoid problems with the setinterval () timer, you can use chained settimeout () to invoke

settimeout (function fn () {
settimeout (fn,interval);
},interval);

This pattern is called settimeout (), and a new timer is created each time the function executes. The second settimeout () invokes the currently executing function and sets another timer for it. The advantage of this is that the new timer code will not be inserted into the queue until the previous timer code is executed, ensuring that there are no missing intervals. Furthermore, it ensures that at least the specified interval is avoided until the next timer code executes, avoiding continuous running

Using SetInterval ()

<div id= "mydiv" style= "height:100px;width:100px;background-color:pink;position:absolute;left:0;" ></div>
<script>
mydiv.onclick = function () {
var timer = setinterval (function () {
if (parseint (myDiv.style.left) >) {
clearinterval (timer);
return false;
}
MyDiv.style.left = parseint (myDiv.style.left) + 5 + ' px '; 
},16); 
}
</script>

 Using chain-type settimeout ()

<div id= "mydiv" style= "height:100px;width:100px;background-color:pink;position:absolute;left:0;" ></div>
<script>
mydiv.onclick = function () {
settimeout (function fn () {
if parseint (myDiv.style.left) <=) {
settimeout (fn,16); 
} else{return
false;
}
MyDiv.style.left = parseint (myDiv.style.left) + 5 + ' px '; 
},16); 
}
</script>

Application

Use timers to adjust the order in which events occur

"1" Web page development, an event occurs first in the child element, and then bubbles to the parent element, the child element's event callback function, which is triggered earlier than the parent element's event callback function. If we first take the event callback function of the parent element first, we need to use settimeout (F, 0)

Normally, click div element, pop 0 first, then pop 1

<div id= "mydiv" style= "Height:100px;width:100px;background-color:pink;" ></div>
<script>
mydiv.onclick = function () {
alert (0);
}
Document.onclick = function () {
alert (1);
}
</script>

If you want the onclick event of document to occur first, that is, click the div element, first eject 1, and then pop 0. The following settings are made

<div id= "mydiv" style= "Height:100px;width:100px;background-color:pink;" ></div>
<script>
mydiv.onclick = function () {
settimeout (function () {
alert (0);
})
}
Document.onclick = function () {
alert (1);
}
</script>

"2" user-defined callback functions, usually triggered before the browser's default action. For example, when a user enters text in an input box, the KeyPress event is triggered before the browser receives text. Therefore, the following callback function is not up to the goal

<input type= "text" id= "Myinput" >
<script>
myinput.onkeypress = function (event) {
This.value = This.value.toUpperCase ();
}
</script>

The code above wants to capitalize the character immediately after the user enters the text. In practice, however, it can only capitalize the last character, because the browser has not received the text at this time, so This.value can't get the most recent typed character

The above code works only if you rewrite it with settimeout.

<input type= "text" id= "Myinput" >
<script>
myinput.onkeypress = function (event) {
settimeout (function () {
myinput.value = MyInput.value.toUpperCase ();
});

The code ends here. The next article to introduce you

BOM series The second installment of the timer Requestanimationframe

BOM series The third timer application (clock, Countdown, stopwatch and alarm clock)

The above mentioned is small set to introduce the BOM series of the first timer settimeout and setinterval, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.