Timer Basics (32)

Keywords: Javascript html5 html

 *  Timer: set a timer and set the waiting time. When the execution time is reached, the browser will execute the corresponding method

 *

 *  [common timer]

 *    setTimeout([function],[interval])

 *    setInterval([function],[interval])

 *

 *        [function]: the method to be executed after the time is reached (the method is not executed when the timer is set, but the time browser helps us execute it)

 *        [interval]: time factor (time to wait)   MS)

 *

 *     setTimeout is a timer that executes once, and setInterval is a timer that can execute multiple times

//=>Execute once
// let count = 0;
// setTimeout(() => {
//     count++;
//     console.log(count);
// }, 1000);

//=>Round robin timer: every INTERVAL of INTERVAL is so long, the set method will be executed again until the timer is cleared
// let count = 0;
// setInterval(() => {
//     count++;
//     console.log(count);
// }, 1000);

//=>Clear timer

//=>clearTimeout  /  clearInterval: either of these two methods can clear timers created by any method

//1. Setting the timer will have a return value. This value is a number, belonging to the number of the timer, which represents the current number of timers (whether the timer is created based on setTimeout or setInterval, this number will be accumulated)

//2.clearTimeout([serial number]) / clearInterval([serial number]): clear the timer set in the browser according to the serial number

// let count = 0;
// let timer = setInterval(() => {
//     count++;
//     console.log(count);
//     if (count === 5) {
//         //=>Clear timer
//         clearTimeout(timer);
//     }
// }, 1000);

Principle of asynchronous programming

 *  Synchronous programming and asynchronous programming in JS

 *     Synchronous programming: tasks are processed in sequence. At present, this thing has not been completely completed, and the next thing cannot be executed

 *     Asynchronous programming: at present, this task has not been completely completed, and we need to wait for a period of time to continue processing. At this time, we don't wait to continue to perform the following tasks. When the subsequent tasks are completed, we can complete the things that have not been completely completed

 *

 *     [asynchronous programming in JS]

 *        1. All event bindings are asynchronous programming     xxx. ο nclick=function(){}

 *        2. All timers are programmed asynchronously   setTimeout(function(){},1000)

 *        3. Asynchronous programming is generally used in Ajax

 *        4. Callback function is also asynchronous programming

 *       ...

// let n = 0;
// setTimeout(() => {
//     console.log(++n);//=>1) 
// }, 1000);
// console.log(n);//=>0) 
//=>The timer sets a time, which may not be executed after the time is reached (if there are other synchronization tasks being processed, you have to wait when the time is up)
// let n = 0;
// setTimeout(() => {
//     console.log(++n);
// }, 1000);
// console.log(n);//=>0
// while(1===1){
//     //=>Dead cycle
// }

//=>How do browsers plan synchronous and asynchronous mechanisms

//1. The browser is multi-threaded and JS is single threaded (the browser only assigns one thread to JS execution): the characteristic of single thread is that it can only handle one thing at a time

//Process: each application can be understood as a process (when the browser opens a page, it is equivalent to opening a process). In a program (process), we often do many things at the same time. At this time, we can assign multiple threads to complete multiple tasks at the same time

//2.JS implements the asynchronous mechanism in a single thread, which mainly depends on the completion of the browser's task queue. There are two task queues in the browser (main task queue and waiting task queue)

// setTimeout(() => {
//     console.log(1);
// }, 20);
// console.log(2);
// setTimeout(() => {
//     console.log(3);
// }, 10);
// setTimeout(() => {
//     console.log(4);
// }, 100);
// for (let i = 0; i < 90000000; i++) {
//
// }
// console.log(5);
//=>2 5 3 1 4


//=>Test procedure response time
// // let startTime = new Date();
// console.time('AA');
// for (let i = 0; i < 90000000; i++) {
//
// }
// // console.log(new Date() - startTime);
// console.timeEnd('AA');

// let n = 0;
// setTimeout(() => {
//     console.log(++n);
// }, 0);//=> Setting the timer time factor to zero is not immediate. Each browser has its own minimum waiting and response time (Google: 5 ~ 6 ie: 10 ~ 13), so writing zero is still asynchronous programming
// console.log(n);

First meet Promise

 *  Promise: it is a newly added class in ES6   (new   Promise) is to manage asynchronous programming in JS, so we also call it "promise design pattern"

// let p = new Promise();
// p.then();

//=>Three statuses: pending (preparation: initialization succeeded, asynchronous task started) \ completed \ rejected

// new Promise(() => {
//     //=>Execute an asynchronous task (when a new Promise is created, an instance of Promise will immediately execute the asynchronous operations in the current function body) = > "Promise is synchronous and it can manage asynchronous operations"
//     setTimeout(() => {
//
//     }, 1000);
//     console.log(1);//=> Output 1 first
// }).then();
// console.log(2);//=> Re output 2

// new Promise((resolve, reject) => {
//     //=>Resolve: when the asynchronous operation is successful, we execute the resolve method
//     //=>Reject: when the asynchronous operation fails, we execute the reject method
//     setTimeout(() => {
//         resolve(100);
//     }, 1000);
// }).then((res) => {
//     //=>The first function passed is resolve
//     console.log('ok', res);
// }, () => {
//     //=>The second passed function is reject
//     console.log('no');
// });
// let val = null;
// let xhr = new XMLHttpRequest();
// xhr.open('get', 'js/1.js', true);//=> True Ajax asynchronous
// xhr.onreadystatechange = () => {
//     if (xhr.readyState === 4 && xhr.status === 200) {
//         val = xhr.responseText;
//         //=>Here is the result. There are many things to do after obtaining the result (at this time, we can only write tasks such as counting and binding here)
//     }
// };
// xhr.send(null);
// console.log(VAL);//=> If an asynchronous Ajax request is used, the VAL is output before AJAX is completely completed, and the result is NULL

let pro = new Promise((resolve, reject) => {
    //=>Perform an asynchronous operation
    let xhr = new XMLHttpRequest();
    xhr.open('get', 'js/1.js', true);
    xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
            val = xhr.responseText;
            resolve(val);
        }
        if (xhr.status !== 200) {
            //=>Fail
            reject();
        }
    };
    xhr.send(null);
});
pro.then((res) => {
    console.log(res);
    //=>Data binding
    return 100;//=>The result it returns is passed to the second THEN
}, () => {
    console.log('no');
}).then((res) => {
    //=>When the function in the first THEN is executed, the second one will be executed
    console.log(res);
}, () => {

}).then(() => {
    //=>When the function in the second THEN is executed, the third one will be executed
}, () => {

});

Posted by mzm on Wed, 29 Sep 2021 13:15:33 -0700