This is the 18th day of my participation in the August Challenge. Check out the August Challenge for details

preface

SetTimeout and setInterval are often used, more or less, but there may be many students who do not understand the relevant in-depth things, and only stay at the level of use. Today we’re going to take a closer look at setTimeout and setInterval.

The use of the setTimeout

Description of MDN:

WindowOrWorkerGlobalScope mixed setTimeout () method set a timer, and execute a function within the timer in the timer expires or the designated a piece of code.

To review how setTimeout is used, let’s look at the following code:

Since the setTimeout method is provided by the browser Window object, we can remove the window.

setTimeout(function() {
	console.log('Dream Chasers');
}, 1000);

/ / equivalent to the
/* window.setTimeout(function() {console.log(' dreamers '); }, 1000); * /
Copy the code

In combination with the above MDN document, setTimeout can also be said to be a delay timer, that is, the second parameter determines how many milliseconds to execute a function or a specified piece of code.

The use of the setInterval

Description of MDN:

WindowOrWorkerGlobalScope setInterval () method calls a function or to perform a code block, has the fixed time delay between each call.

Again, to review how setInterval is used, let’s take a look:

setInterval (function() {
    console.log('Dream Chasers');
}, 1000);
Copy the code

The code above, in fact, is every 1000 milliseconds, and then executes the corresponding function to print “dream chaser”.

The first argument can be a string

If you use setTimeout, the first argument is always the pass function. Pass string, this form, you should be less used, so let’s see:

setTimeout("Console. log(' Dream chasers ');".1000);
Copy the code

This way, it is relatively rare, why not?

Compiling and executing strings after delay milliseconds (this syntax is not recommended for the same security reasons as eval()).

In fact, if the first argument is a string, it is equivalent to executing an eval() method to execute code.

The return value of setTimeout

Note: The example here is setTimeout, and the same is true for setInterval. TimeroutID, the return value of setTimeout, is a positive integer, indicating the timer number.

var timer1 = setTimeout(function() {
  console.log('Dream Chasers');
}, 1000);
var timer2 = setTimeout(function() {
  console.log('Dream Chasers');
}, 1000);
var timer3 = setTimeout(function() {
  console.log('Dream Chasers');
}, 1000);

console.log(typeof timer1);
console.log(timer1, timer2, timer3);
Copy the code

The output can be seen below

Question. So how do we cancel the timer?

The return value timeroutID from the above execution method can be passed to clearTimeout to cancel the timer.

var timer1 = setTimeout(function() {
  console.log('Dream Chasers');
}, 1000);
clearTimeout(timer1);
Copy the code

Type this code into the console, and run it, and you’ll see that the console doesn’t print “Dream Chasers”. The timer has been disabled.

Note: To cancel the timer using setInterval, use the clearInterval method. Use the same as clearTimeout.

Parameter transfer problem

So when we use the setTimeout method and we want to pass in the parameter, what do we do?

Let’s try it first:

var timer1 = setTimeout(function (. args) {
  console.log('args', args);
}, 1000.1.2.3.4.5.6);
Copy the code

What do you think of the above approach? It looks like you can pass the parameter. Is there a more elegant way? There is.

function test(. args) {
  console.log('args', args);
}
var timer1 = setTimeout(function () {
  test(1.2.3.4.5.6);
}, 1000);
Copy the code

In the first function of setTimeout, put a test function and execute it, passing in the corresponding argument.

This points to the

So what is implicit loss?

Implicit loss is when a function that is implicitly bound loses its bound object. This situation is error-prone but common. Why? Because JavaScript functions can be passed around as arguments as well as return values, you lose the “this” reference and get confused.

Let’s look at an example:

var obj = {
  a: function() {
    console.log(this); }}var test = obj.a;
test();
Copy the code

The output is the window object. If we execute obj. A directly without assigning, the output is the obj object, which is implicitly lost in the assignment.

Implicit loss can also occur with setTimeout/setInterval methods.

var obj = {
  a: function() {
    console.log(this); }};setTimeout(obj.a, 1000);
Copy the code

The output is also a window object, so how do I solve the problem that this refers to?

There are two ways:

  1. Bind this of obj. A to obj using the bind method
  2. The obj. A function is executed in an anonymous function in the timer

The specific code can be seen below

1 / / way
setTimeout(obj.a.bind(obj), 1000);

2 / / way
setTimeout(function() {
  obj.a();
}, 1000);
Copy the code

The time interval

The HTML5 standard says

  • The minimum time interval for setTimeout is 4 milliseconds
  • SetInterval has a minimum interval of 10 milliseconds, which means that intervals less than 10 milliseconds will be adjusted to 10 milliseconds

The background model

Most computer monitors refresh at 60 Hz, which equates to about 60 redraws per second. Therefore, the optimal cycle interval for the smoothest animation effect is 1000ms/60, which is approximately 16.6ms.

To save power, the browser increases the interval to 1,000 milliseconds for pages that are not in the current window.

In addition, if the laptop is on battery power, Chrome and IE9 and later will switch the interval to the system timer, which is about 16.6 milliseconds.

Wrote last

This article mainly let you understand setTimeout and setInterval related knowledge:

  • The first argument can be a string
  • The return value of setTimeout
  • Parameter transfer problem
  • This points to the
  • The time interval

If there are any mistakes in this article, please correct them in the comments section. If this article helped you or you liked it, please like it and follow it.