Interviewer: “Do you know about timers?”

Me: “Yes”

Interviewer: “Tell me what a timer is.”

Me: “Timers can be implemented with setTimeout.”

SetTimeout (function () {console.log(“1”)},0);

console.log(“2″); What is the output order on the console?”

I: prevaricate……

so…. There is this article, nagging so long, the body begins!

Syntax functions of setTimeout:

The setTimeout() method is used to call a function or evaluate an expression after a specified number of milliseconds

To illustrate the above statement, here’s a simple example:

<! DOCTYPE html> <head> <title>setTimeout</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
    <h1>setTimeout</h1>
    <span id="content"</span> <script>setTimeout(function () {
           let content = document.getElementById('content');
           content.innerHTML = "
      
One second later
"
; }, 1000); </script> </body> </html>Copy the code

The span TAB changes from “test” to “one second later.”

Timer function:

To achieve:

<! DOCTYPE html> <head> <title>setTimeout</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
    <h1>setTimeout</h1>
    <span id="content"< span style = "max-width: 100%; clear: both; min-height: 1em"start()"</button> <script> var x = 00, y = 00, z = 00;function start () {
            if (x<= 59 && x>=0 && y<=59 && y>=0 && z<=59 && z>=0) {
               let content = document.getElementById('content');
               content.innerHTML = z + ":" + y + ":" + x;
               console.log(x);
               x = x + 1;
            } else if (y<=59 && y>=0 && z<=59 && z>=0) {
                y = y + 1;
                x = 0;
            } else if (z<=59 && z>=0){
                z = z + 1;
                x = 0;
                y = 0;
            }
            setTimeout ("start()", 1000); } </script> </body> </ HTML >Copy the code

Console output:

Here, the start() function is executed after the click, and inside the function setTimeout() calls start(), so it calls start() once a second.

SetTimeout () :

We all know that setInterval() and setTimeout() can take two arguments. The first argument is the function that needs to be called back, which must be passed in, and the second argument is the time interval, the number of milliseconds, which can be omitted. But it can actually receive more parameters, so what are those parameters for? The arguments passed to the callback function, starting with the third argument.

Example:

setTimeout(function(a,b){ console.log(0+a+b); 7},1000,3,4);Copy the code
Note: Internet Explorer 9.0 or later only allows setTimeout to have two parameters, not more parameters

If you want to pass parameters to a callback function, you can use bind(). eg:

setTimeout( function(a, b) {}. The bind (3, 4), 1000);Copy the code
So how do I get rid of the timer? Don’t worry, don’t worry, I’ll tell you!

clearTimeout():

The setTimeout function returns an integer number representing the counter number, which is passed to the clearTimeout function to cancel the corresponding timer.

ClearTimout () has the following syntax: clearTimeout(timeoutID) To use clearTimeout(), we set setTimeout() to give this setTimout() a name, This name is timeoutID, and when we stop, we’re going to stop with this timeoutID, which is a custom name.

Usage:

var id1 = setTimeout(f,1000); //id1 is timeoutID var id2 =setInterval(f,1000); //id2 is timeoutID clearTimeout(id1); clearInterval(id2);Copy the code

The this of setTimeout() points to:

For javascript this pointing problem, before also puzzled me for a long time, oh, where is so difficult, in fact, in a word: who calls is pointing to whom ah! This means who is calling this is referring to.

Let’s put it this way:

var x = 1;
var obj = {
  x: 2,
  y: function(){ console.log(this.x); }};setTimeout(obj.y,1000); / / 1Copy the code

why? The object that is called refers to the object that is called, and the setTimeout function calls the y method in the obj object, which is called by setTimeout, yes, that’s right, it’s called by setTimeout, But the setTimeout function belongs to the window, you know, so the setTimeout object is the window, so everything makes sense.

Got it? Here’s a quiz. Ready to take it!
function Animal(login) {
  this.login = login;
  this.sayHi = function() {
    console.log(this.login);  //undefined
  }
}
var dog = new Animal('John');
setTimeout(dog.sayHi, 1000);

Copy the code

Ha ha ha, that’s right, wow 👋, but no reward 😂

When dog.sayhi is executed, it is executed in a global object, but this.login does not get a value.

The delay time of setTimeout() is 0

To answer the questions the interviewer asked me 😂. Wow, blood lessons, come to come a little bit more direct chestnuts:

    console.log('a');
    setTimeout(function(){
    console.log('b'); }, 0); console.log('c');
    console.log('d');
Copy the code

Console output: A, C, D, and B. You know why? Theoretically he has a zero delay and should do it right away? No. As stated by the setTimeout operation mechanism, the task specified by setTimeout will not be executed until the synchronization task of the current script and the existing events in the “task queue” are all processed. In other words, what setTimeout really does is to add an event to an existing event in the “task queue”, specifying that a certain piece of code should be executed at a specified time. SetTimeout Adds an Event that will be executed in the next Event Loop. Well, for those of you who are not clear about the event loop, take a look at the Nguyen Yifeng -avaScript runtime mechanism for details

What else is missing from setTimeout

SetTimeout () in the event loop:

As we all know, Javascript engines (JS engines) are single-threaded and can only perform one task at a particular time and block the execution of other tasks, that is, these tasks are serial. In this case, the user has to wait for a time-consuming operation to complete before proceeding to the next operation, which is obviously unacceptable, but can be solved with asynchronous code in real development.

When asynchronous methods, such as setTimeout() here, or Ajax requests or DOM events are executed, they are managed by other modules in the browser kernel. When the asynchronous method meets the trigger condition, the module will push the method into a task queue. When the main thread code is idle after execution, it will check the task queue, push the first task in the queue to execute, and continue checking the task queue after completion, and so on. The premise is that the main thread is idle, which is the model of the event loop.

Serious talk of a wave of theory, chestnuts:

setTimeout(function () {
    console.log("b");
},0)
console.log("a");
Copy the code

SetTimeout () is executed in a task queue. After the main thread completes the main thread, setTimeout() is executed in the task queue.

Same idea:

setTimeout(function(){ console.log(1111); }, 0)while (true) {};
Copy the code

The console will never output anything, because the main thread has created an infinite loop, the main thread is never idle, it will not execute the setTimeout function in the task queue. Understanding setTimeout() once and for all

Conclusion:

Having said that, setTimeout is not very powerful, lol. However, if you can not master, do not recommend multi-use. After all, there are situations in which setTimeout exists as a hack.

Here, first of all, congratulations, should be full of harvest. Secondly, you can like 😜