BOM programming ② (timer, execution queue)

Time:2022-4-11

timer

Two kinds of timers

Window object provides us with two very useful methods – timer

  • setTimeout()
  • setInterval()

Settimeout() timer

Syntax:

window. SetTimeout (calling function, [number of milliseconds delayed]);

The setTimeout () method is used to set a timer that executes the calling function after the timer expires. (just like a time bomb)

be careful:

  • Window can be omitted
  • This calling function canDirect write function, orWrite function nameOr takeString 'function name ()'Three forms. The third is not recommended
  • The number of milliseconds of delay is omitted. The default is 0. If it is written, it must be milliseconds
  • Because there may be many timers, we often assign an identifier to the timer

Extension:
The calling function setTimeout () is also called callback function

Ordinary functions are called directly in code order. This function needs to wait until the time is up, so it is called a callback function.

Simple understanding: callback means to call back. After the last thing is done, call this function again later.

Previously involved element Onclick = function() {} or element addEventListener(“click”, fn); The function inside is also a callback function

Stop settimeout() timer

window.clearTimeout(timeoutID)

The cleartimeout() method cancels the timer previously established by calling settimeout()
be careful:

  • Window can be omitted
  • The parameter inside is the identifier of the timer

Setinterval() timer

Syntax:

window. Setinterval (callback function, [milliseconds of interval]);

Setinterval () method calls a function repeatedly, and calls the callback function every other time.
be careful:

  • Window can be omitted
  • This calling function canDirect write function, orWrite function nameOr takeString 'function name ()'Three forms.
  • If the number of milliseconds of the interval is omitted, the default is 0. If it is written, it must be milliseconds, which means that this function will be called automatically every few milliseconds.
  • Because there may be many timers, we often assign an identifier to the timer.
  • The first execution is also executed after milliseconds, and then every milliseconds.

Case: Web page countdown (three black boxes store hours, minutes and seconds respectively)

<body>
    <div class = 'hour'></div>
    <div class="minute"></div>
    <div class="second"></div>
    <script>
        let hour = document.getElementsByClassName('hour')[0];
        setInterval(function(){
            let time = new Date();
            hour.innerHTML = time.getHours();
            hour.nextElementSibling.innerHTML = time.getMinutes();
            hour.nextElementSibling.nextElementSibling.innerHTML = time.getSeconds();
        },1000);
    </script>
</body>

be careful:
① This date object cannot be placed outside the callback function, otherwise it will get a static time, and the time will not change with the callback.
② If you don’t want the blank when the page first opens, you can call the function once first.

Stop setinterval() timer

window.clearInterval(intervalID);

The clearinterval () method cancels the timer previously established by calling setinterval ()
be careful:

  • Window can be omitted
  • The parameter inside is the identifier of the timer

Case: sending SMS
After clicking the button, the button cannot be clicked again within 60 seconds to prevent repeated sending of short messages
BOM programming ② (timer, execution queue)
Idea:
① After the button is clicked, disabled will be disabled and set to true
② At the same time, the content in the button will change. Note that the content in the button can be modified through innerHTML
③ There are changes in the number of seconds, so a timer is needed
④ Define a variable, which decreases continuously in the timer
⑤ If the variable is 0, it means that it is time. We need to stop the timer and restore the initial state of the button.

Code implementation:

<body>
    <input type="text">
    < button > send < / button >
    <script>
        let button = document.getElementsByTagName('button')[0];
        button.onclick = function(){
            Alert ('SMS has been sent ');
            button.disabled = true;
            let count = 10;
            let huidiao = function(){
                button. InnerHTML = count + 'resend in seconds';
                if(count == 0){
                    clearInterval(jishi);
                    button.disabled = false;
                    button. InnerHTML = 'send';
                }
                count--;
            };
            huidiao();
            let jishi = setInterval(huidiao,1000);
        }
    </script>
</body>

this

The point of this cannot be determined when the function is defined. Only when the function is executed can we determine who this points to. Generally, this finally points to the object that calls it

At this stage, let’s first understand some of this points

  1. In the global scope or ordinary function, this points to the global object window (note that this in the timer points to the window)
  2. Who calls this in the method call
  3. This in the constructor points to an instance of the constructor
<body>
    < button > Click < / button >
    <script>
        //This points to the problem. Generally, the final point of this is the object that calls it

        // 1.  In the global scope or ordinary function, this points to the global object window (note that this in the timer points to the window)
        console.log(this);

        function fn() {
            console.log(this);

        }
        window.fn();
        window.setTimeout(function() {
            console.log(this);

        }, 1000);
        // 2.  Who calls this in the method call
        var o = {
            sayHi: function() {
                console. log(this); //  This refers to o this object

            }
        }
        o.sayHi();
        var btn = document.querySelector('button');
        // btn.onclick = function() {
        //     console. log(this); //  This refers to the BTN button object

        // }
        btn.addEventListener('click', function() {
                console. log(this); //  This refers to the BTN button object

            })
            // 3.  This in the constructor points to an instance of the constructor
        function Fun() {
            console. log(this); //  This refers to the fun instance object

        }
        var fun = new Fun();
    </script>
</body>

JS execution mechanism

JS is single threaded

A major feature of JavaScript language is single thread, that is, you can only do one thing at a time. This is due to the mission of the birth of JavaScript, a scripting language – Javascript was born to deal with user interaction in pages and operate dom. For example, we can’t add and delete a DOM element at the same time. You should add it first and then delete it.

Single thread means that all tasks need to be queued, and the next task will be executed only after the previous task is completed. The problem caused by this is: if JS is executed for a long time, it will cause the rendering of the page to be inconsistent, resulting in the feeling of page rendering loading blocking.

For example:
The execution result of the following code is 123

 console.log(1);
 setTimeout(function () {
   console.log(3);
 }, 1000);
 console.log(2);

Synchronous and asynchronous

In order to solve this problem, using the computing power of multi-core CPU, HTML5 proposes the web worker standard, which allows JavaScript scripts to create multiple threads. So, in JSsynchronizationandasynchronous

synchronization
Execute the next task after the previous task is completed. The execution order of the program is consistent and synchronized with the sequence of tasks. For example, the synchronous method of Cooking: we need to boil water and cook. When the water boils (10 minutes later), we can cut and fry vegetables.

asynchronous
When you are doing something, because it will take a long time, you can deal with other things while doing it. For example, in the asynchronous method of cooking, we use this 10 minutes to cut and fry vegetables while boiling water.

Their essential difference: the execution order of each process on this pipeline is different

Synchronous and asynchronous tasks

Synchronization task
Synchronization tasks are executed on the main thread to form an execution stack.

Asynchronous task
The asynchrony of JS is realized through callback function.

Generally speaking, there are three types of asynchronous tasks:
1. Common events, such as click, resize, etc
2. Resource loading, such as load, error, etc
3. Timer, including setinterval, setTimeout, etc
Asynchronous task related callback functions are added to the task queue (also known as message queue).

For example: the following code

 console.log(1);
 setTimeout(function () {
   console.log(3);
 }, 0);
 console.log(2);

BOM programming ② (timer, execution queue)

JS execution mechanism

  1. First execute the synchronization task in the stack.
  2. The asynchronous task (callback function) is put into the task queue.
  3. Once all the synchronous tasks in the execution stack are executed, the system will read the asynchronous tasks in the task queue in order, so the read asynchronous tasks end the waiting state, enter the execution stack and start execution.

BOM programming ② (timer, execution queue)
For example, the following code:

 console.log(1);
 document.onclick = function() {
   console.log('click');
 }
 console.log(2);
 setTimeout(function() {
   console.log(3)
 }, 3000)

BOM programming ② (timer, execution queue)
Because the main thread repeatedly obtains, executes, re obtains and re executes tasks, this mechanism is called event loop

be careful:
① The event loop can ensure that no task in the asynchronous queue is ignored and missed
② Asynchronous process processing plays the role of controlling asynchronous tasks to enter the asynchronous queue:
After the click is detected in the above code, he will put the callback function into the asynchronous queue
After 3 seconds, he will put the corresponding callback function into the asynchronous queue.