The difference between parallelism and concurrency
Concurrency is A macro concept, which refers to the completion of tasks A and B by switching within A period of time. This is called concurrency
Parallelism is A microscopic concept. It refers to the existence of two cores in A CPU that simultaneously complete two tasks, A and B, called parallelism
Callback function, callback hell
Juejin. Cn/post / 684490…
The word callback hell, his emphasis is on ‘callback’, and callback is most used in JS, of course, asynchronous programming
What ‘callback hell’ means by nesting is asynchronous nesting
This brings up two problems: readability and trust
Readability problem
When we write business logic, it looks like this
listen( "click".function handler(evt){
doSomething1();
doSomething2();
doSomething3();
doSomething4();
setTimeout( function request(){
doSomething8();
doSomething9();
doSomething10();
ajax( "http:// some. url. 1".function response( text){
if (text == "hello") {
handler();
} else if (text == "world") { request(); }}); doSomething11(); doSomething12(); doSomething13(); },500);
doSomething5();
doSomething6();
doSomething7();
});
Copy the code
These are all things, some of them are synchronous, some of them are asynchronous, and it’s hard to read because you have to remember the order in which they’re executed
This is the readability problem with asynchronous nesting, which is caused by the operation mechanism of asynchronous nesting
Trust issues
The focus here is on asynchronous callbacks
Possible problems:
- The callback premature
- Callback too late or no callback
- The callback for many times
- The root of such problems lies in inversion of control, which is dependency injection in object-oriented applications, which realizes decoupling between modules.
In the case of callbacks, it’s not friendly, and control is handed over to a third party, who decides when and how to call the callback
How does Promise solve these two problems
Solve readability problems
A Promise gives you a rough sheet of paper on which to write down ideas for solving a problem, without mentally jotting down the order of execution
Solving trust Issues
Promise doesn’t cancel the inversion of control, it just reverses it
This is a bit like an event trigger, which differs from a normal callback in that:
Normally, successful callback operations are written directly into the callback function, and the invocation of these operations is controlled by a third party.
In Promise, the callback is only responsible for the notification of success, and the action after success is placed in the callback of THEN, which is precisely controlled by Promise
- The problem with premature pullbacks
Because promises are asynchronous, there are no asynchronous synchronous calls, and even errors before the resolution are asynchronous, without the hassle of synchronization (calling too early)
var a = new Promise((resolve, reject) = > {
var b = 1 + c; // ReferenceError: c is not defined, the error will be reported after a is printed below.
resolve(true);
})
console.log(1, a);
a.then(res= > {
console.log(2, res);
})
.catch(err= > {
console.log(err);
})
Copy the code
- The callback is too late, there is no callback problem
Promises are not called back too late, but once they are made, they will work as promised. For network or server problems, promises don’t solve them, and typically use Promise’s race API promise.race with a timeout
function timeoutPromise(delay) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject("Timeout!");
}, delay);
});
}
Promise.race([doSomething(), timeoutPromise(3000)]) .then(...) .catch(...) ;Copy the code
- For too few or too many callbacks
Since promises can only be made once and cannot be changed after the resolution, even multiple callbacks do not affect the result and subsequent calls are ignored
Common timer function
Common timer functions: setTimeout, setInterval, requestAnimationFrame
The minimum delay interval for setTime and setInterval is 4ms (W3C stipulated in HTML standard). Nothing in JS executes immediately, but as soon as the process is idle. This means that both setTimeout and setInterval are set for n milliseconds to be added to the queue, rather than executed immediately after n milliseconds
setInterval
Every once in a while, the callback function is executed
Disadvantages:
SetInterval adds an event to the queue every 100ms. After 100ms, it adds the T1 timer code to the queue. There are still tasks in the main thread, so it waits. The T2 timer was added to the queue. The main thread is still running T1, so wait. After another 100ms, the theory should push a timer code into the king queue, but since T2 is still in the queue, T3 will not be added, so it will be skipped, and T2 will be executed immediately after T1
- As with setTimeout, there is no guarantee that the task will be executed at the expected time
- Certain intervals may be skipped
- Multiple timers may be executed consecutively and not achieve the effect of the timer
function demo() {
setInterval(function(){
console.log(2)},1000)
sleep(2000)
}
demo()
Copy the code
In the above code, if a time-consuming operation occurs during the execution of the timer, multiple functions will be executed at the same time after the time-consuming operation, which will cause performance problems
setTimeout
False: setTime is executed as long as it is delayed, but this is actually wrong
Because JS is single threaded, if the previous code affects the performance, setTimeout will not be executed on time. Of course, we can modify setTimeout through the code to make the timer relatively accurate
let period = 60 * 1000 * 60 * 2; // Two hours
let startTime = new Date().getTime();
let count = 0;
let end = new Date().getTime() + period;
let interval = 1000;
let currentInterval = interval; CurrentInterval and interval are both one second
function loop() {
count++;
let offset = new Date().getTime() - (startTime + count * interval);
let go = function () {
currentInterval = interval - offset;
console.log('Code execution time:' + offset, 'Next cycle interval' + currentInterval);
setTimeout(loop, currentInterval);
}
setTimeout (go(), 400);
// Get the time for the next loop
}
setTimeout(loop, currentInterval);
Copy the code
But it’s good compared to setInterval
- No new timer is inserted into the queue until the previous timer runs out (resolve defect 1)
- Determine timer interval (solve problem 2)
requestAnimationFram
RequestAnimationFram solves the problem that browsers don’t know when javaScript animations start and don’t know the optimal loop spacing
The speed of a requestAnimationFrame is determined by the browser, and different browsers will determine the best frame efficiency.
- advantages
- SetAnimationFram has its own function throttling function, which can be executed only once in 16.6 milliseconds (without dropping frames).
- And the delay effect of the function is accurate, no other timer time is not accurate
- basis
- Accept a callback function as an argument
window.requestAnimationFrame(callback)
Copy the code
- When the callBack is executed, its argument is a high-progress timestamp passed by the system in milliseconds, representing the time until the web page is loaded
- Window. RequestAnimationFram () returns an integer, the integer can be introduced into the window. The requestAnimationFram (), is used to eliminate the implementation of the callback function