How JavaScript works

  • 1. What are threads

Thread is the smallest unit that the operating system can schedule operations. It is contained in the process and is the actual operating unit in the process. A thread is a single sequential flow of control in a process, and multiple threads can be concurrent in a process, each performing a different task in parallel

  • 2. Similarities and differences between JavaScript execution mechanisms and other execution mechanisms

As a browser scripting language, JavaScript was originally developed to serve user operations and browser DOM. However, multithreading has a series of problems such as resource preemption, deadlock and conflict between threads. This dictates that JavaScript must be single-threaded, or else there will be a collision problem. So all browsers’ JS engines (which the browser uses to read and execute JavaScript) only allocate one thread to execute JavaScript. While single-threading is not a conflict problem, it also introduces a new problem — blocking

console.log(1)

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

new Promise(function(resolve){
    resolve()
}).then(function(){
    console.log(3)})console.log(4)
Copy the code

Timers are a double-edged sword

Timers: Used to execute a specific block of code at a specific time. Common timers are setTiemout, setInterval, setImmediate, requestAnimationFrame.

  • 1. Use a timer
    • SetTiemout (timeout call, executed only once)
    • SetInterval (called at intervals, always executed if nothing is done)
    • SetImmediate (Executes the specified function immediately after the browser has completely finished the currently running action (implemented only in IE10 and Node 0.10+), similar to setTimeout(func, 0))
    • RequestAnimationFrame (API specifically designed for high performance frame animation, but can not specify a delay time, but depending on the browser refresh rate (frame))
  • 2. How to clear the timer in time
    • window.clearInterval
  • 3. Use CSS3 animation wisely
    • If you can use CSS3 animation, try not to use timers to achieve

Timer using —- anti – shake function

const debounce = (func, delay = 200) => {
  let timeout = null
  return function () {
    clearTimeout(timeout)
    timeout = setTimeout(() => {
      func.apply(this, arguments)
    }, delay)
  }
}
Copy the code

Binding of events

  • 1. Make use of event proxy delegates
    • <input onclick=”myAlert()” type=”button” value=”” />
    • Binding in code

<script type="text/javascript">
  function myAlert(){
  alert("Bicycle");
  </script>

Copy the code
  <input id="demo" type="button" value=""/> <script type="text/javascript"> document.getElementById("demo").onclick=function(){ alert(this.getAttribute("type"));  // This refers to the HTML element of the current event, in this case the <div> tag}Copy the code
  • 2. Avoid repeated event listening

Event delegation


<ul id="ul1">
    <li>111</li>
    <li>222</li>
    <li>333</li>
    <li>444</li>
</ul>

window.onload = function(){
    var oUl = document.getElementById("ul1");
    var aLi = oUl.getElementsByTagName('li');
    for(var i=0; i<aLi.length; i++){ aLi[i].onclick =function(){
            alert(123); }}}// Event delegate
window.onload = function(){var oUl = document.getElementById("ul1"); oUl.onclick =function(ev){var ev = ev || window.event;vartarget = ev.target || ev.srcElement;if(target.nodeName.toLowerCase() == 'li'{alert ()123); Alert (target. InnerHTML); }}}Copy the code
  • 3. Event capture and event bubbling

What are event capture and event bubbling?

Event capture and event bubbling are Netscape and IE’s descriptions of the order in which DOM events are generated. Netscape assumes that events received by the DOM should be first received by the Window, then sequentially by sequentially, and finally by the specific element: event capture. IE says DOM events should be received first by the concrete element, then sequentially, and finally by the Window: event bubbling. In the end, W3C has unified the two approaches, namely, DOM events are divided into two phases, the event capture phase and the event bubble phase, for example: When an element on the page is clicked, there is an event capture phase, in which the Window receives the event first, then captures it section by section, then receives it section by section, then receives it section by section by section, then receives it section by section by section by section by section, and finally the window receives the event again. The following is a diagram of DOM event flow

Some good javascript hierarchy ideas

  • 1. Jquery ready with native wondow. Onload
  • 2. Component lifecycle of the MVVM framework
  • 3. Variable caching and privatization

Using hash objects makes it easier to query arrays

// Merge array A and array B
let array = [{
    id: 1.name: '123123123'}, {id: 2.name: '123123123'}, {id: 3.name: '123123123'}, {id: 4.name: '123123123'}, {id: 5.name: '123123123'
}]
let b = [{
    id: 1.age: 19}, {id: 2.age: 19}, {id: 3.age: 19}, {id: 4.age: 19}, {id: 5.age: 19
}]


// Merge array A and array B, if we do not transform the intelligence through the loop n2
array.forEach(p= > {
    b.find(j= >{})})// If converted to hash object, this complexity programming n
let c = {} 
b.forEach(p= > {
    c[p.id] = p
})

array.forEach(p= > {
    p.age = c[p.id].age
})


Copy the code