JavaScript event execution mechanism

JS event execution mechanism

1, JS event knowledge

1.1 registration event (2 methods)

Adding an event to an element is called a registration event or a binding event

There are two ways to register events: traditional method and listening registration method

Traditional registration method:

utilize on Start event onclick

 <button onclick="alert("hi~")"></button>
 btn.onclick=function(){}
  • Features: uniqueness of registration events

  • Only one handler can be set for the same element and event. The last registered handler will overwrite the previously registered handler

Listening registration method

  • w3c standard recommendation

  • Addeventlistener() is a method

  • Ie before IE9 does not support this method. attachEvebt() can be used instead

  • Features: multiple listeners can be registered for the same element and event

  • Execute in order of registration

1.2 event monitoring

Addeventlistener() event listener (supported after IE9)

 eventTarget.addEventListener(type,listenner[,useCaoture])

The method accepts three parameters:

Type: event type string, such as click and mouseover. Note that on is not included

listener: event handling function, which will be called when an event occurs

useCapture: optional parameter. It is a Boolean value. The default value is false.

Example:

    
 <button>Traditional registration events</button>
     <button>Method listens for registration events</button>
     <script>
         var btns = document.querySelectorAll('button');//Select elements through selectors
         // 1. Traditional registration events
         btns[0].onclick = function () {
             alert('hi');
         }
         // 2. Event listener registers the event addEventListener 
         // (1) The event type inside is a string. It must be quoted without on
         // (2) Multiple listeners (event handlers) can be added to the same element and the same event
         btns[1].addEventListener('click', function () {
             alert(22);
         })
         btns[1].addEventListener('click', function () {
             alert(33);
         })
 ​
     </script>

1.3 common mouse events

Mouse eventTrigger condition
onclickClick the left mouse button to trigger
onmouseoverMouse over trigger
onmouseoutMouse left trigger
onfocusGet mouse focus trigger
onblurLoss of mouse focus trigger
onmousemoveMouse movement trigger
onmouseupMouse bounce trigger
onmousedownMouse press trigger

1.4 event object

Event is an event object

event.target is the object that returns the trigger event

1.5 mouse event object

(1) Basic grammar

An event object is a collection of information related to an event

Mouse event objectexplain
e.clientXReturns the X coordinate of the mouse relative to the viewable area of the browser window
e.clientYReturns the Y coordinate of the mouse relative to the viewable area of the browser window
e.pageXReturn the X coordinate of the mouse relative to the document page IE9 + support
e.pageYReturn the Y coordinate of the mouse relative to the document page IE9 + support
e.screenXReturns the X coordinate of the mouse relative to the computer screen
e.screenYReturns the Y coordinate of the mouse relative to the computer screen

Example: obtain the coordinates of the mouse on the page

 <script>
         // Mouse event object MouseEvent
         document.addEventListener('click', function (e) {//By listening to events
             // 1. x and y coordinates of the client mouse in the visual area
             console.log(e.clientX);
             console.log(e.clientY);
             console.log('---------------------');
 ​
             // 2. The page mouse is on the x and y coordinates of the page document
             console.log(e.pageX);
             console.log(e.pageY);
             console.log('---------------------');
 ​
             // 3. screen the x and y coordinates of the mouse on the computer screen
             console.log(e.screenX);
             console.log(e.screenY);
 ​
         })
 </script>

1.6 common keyboard events

1.1.1 keyboard events

Keyboard eventsTrigger condition
onkeyupTriggered when a keyboard key is released
onkeydownTriggered when a keyboard key is pressed
obkeypressTrigger when a keyboard key is pressed note: function keys such as ctrl shift cannot be recognized

be careful:

1. If you use addEventListener, you do not need to add on

2. The difference between onkeypress and the previous two: it cannot recognize function keys, such as left and right arrows, ctrl, shift, etc

3. The execution sequence of the three events is: keydown--keypress--keyup

Example:

 
<script>
         // Common keyboard events 
         //1. Triggered when the Keyup button pops up 
         document.addEventListener('keyup', function () {//Listening event trigger
             console.log('I bounced up');
         })
 ​
         //3. When the keypress key is pressed, the unrecognized function key is triggered, such as the left and right arrows of ctrl shift
         document.addEventListener('keypress', function () {//Listening event trigger
             console.log('I pressed press');
         })
         //2. When the Keydown key is pressed, it triggers a function key that can be recognized, such as ctrl shift Left and right arrows
         document.addEventListener('keydown', function () {//Listening event trigger
             console.log('I pressed down');
         })
         // 4. Execution sequence of three events keydown -- keypress -- keyup
 </script>

2, BOM

2.1 what is BOM

  BOM (Browser Object Model) is the Browser Object Model. It provides an object that interacts with the browser window independent of content. Its core object is window. BOM consists of a series of related objects, and each object provides many methods and attributes.

DOM

  • Document object type

  • DOM is to write a document as an object

  • The top-level object of DOM is document

  • DOM mainly learns how to manipulate page elements

  • DOM is the W3C Standard Specification

BOM

  • Browser object type

  • Treat the browser as an object

  • The top-level object of BOM is window

  • BOM learns some objects that interact with the browser window

  • BOM is defined by browser manufacturers on their respective browsers, with poor compatibility

2.2 composition of BOM

BOM is larger than DOM, which contains dom

(1) Timer (two types)

  • setTimeout()

  • setInerval()

setTimeout() bomb timer

Turn on the timer

Window.settimeout (calling function, [milliseconds delayed]);

The calling function setTimeout () is also called callback

be careful:

1.window can be omitted

2. This calling function can be written directly to the function, or the function name or the string 'function name ()' -- three methods are not recommended

3. The number of milliseconds delayed is omitted. The default is 0. If it is written, it must be milliseconds

4. Because there may be many timers, we often assign an identifier to the timer.

  Ordinary functions are called directly in code order.
  Simple understanding: callback means calling back. After the last thing is done, call this function again later.
  For example, the calling function, event handling function and callback function in the timer.
  element.onclick = function(){}     Or element.addEventListener("click", fn);    The function inside is also a callback function.

Example:

 <script>
         // The callback function is an anonymous function
         setTimeout(function () {
             console.log('time out');
 ​
         }, 2000);
         function callback() {
             console.log('It exploded');
         }
         // The callback function is a well-known function
         var timer1 = setTimeout(callback, 3000);
         var timer2 = setTimeout(callback, 5000);
 </script>

Case: close the advertisement after 5 seconds

 
<body>
     <img src="images/ad.jpg" alt="" class="ad">
     <script>
         // Gets the element to operate on
         var ad = document.querySelector('.ad');
         // Turn on the timer
         setTimeout(function() {
             ad.style.display = 'none';
         }, 5000);
     </script>
 </body>

Stop Timer

 window.clearTimeout(timeoutID)

The clearTimeout() method cancels the timer previously established by calling setTimeout().

be careful:

1.window can be omitted

2. The parameter inside is the identifier of the timer.

Example:

 
<button>Click stop timer</button>
     <script>
         var btn = document.querySelector('button');//Listening event trigger
         // Turn on the timer
         var timer = setTimeout(function () {
             console.log('It exploded');
         }, 5000);
         // Register click events for buttons
         btn.addEventListener('click', function () {//Listening event trigger
             // Stop Timer 
             clearTimeout(timer);
         })
     </script>

setInterval() alarm timer

Turn on the timer

Window.setinterval (callback function, [milliseconds of interval]);

The setInterval() method calls a function repeatedly, and calls the callback function every other time.

be careful:

1.window can be omitted

2. This calling function can be written directly to the function, or the function name, or take the form of string 'function name ()'

3. If the number of milliseconds in 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 milliseconds

4. Because there may be many timers, we often assign an identifier to a timer

5. The first execution is also executed after the interval of milliseconds, and then every milliseconds

Example:

 
<script>
         // 1. setInterval 
         setInterval(function () {
             console.log('Continue output');
         }, 1000);
     </script>

Case: Countdown

 <style>
         * {
             margin: 0;
             padding: 0;
         }
         div{
             background-color: red;
             width: 300px;
             height: 100px;
             margin: 0 auto;
         }
         div>span {
             display: inline-block;
             width: 50px;
             height: 50px;
             background-color: #000;
             color: white;
             font-size: 25px;
             text-align: center;
             line-height: 50px;
            margin-left: 15px;
            margin-top: 10px;
         }
         div>p{
             color: white;
             text-align: center;
             font-size: 24px;
             font-weight: 400;
         }
     </style>
 </head>
 ​
 <body>
     <div>
         <p>The game is still far from the end</p>
         <span class="day">1</span>
         <span class="hour">2</span>
         <span class="minute">3</span>
         <span class="second">4</span>
     </div>
 ​
     <script>
         //Get element
         var day = document.querySelector('.day');//Get box for days
         var hour = document.querySelector('.hour');//Get hour box
         var minute = document.querySelector('.minute');//Get a box of minutes
         var second = document.querySelector('.second');//Gets the number of seconds in the box
         //Create a new variable to store the total number of milliseconds returned by the user
         var inputTime = new Date('2021-10-07 12:00:00');
 ​
         time();//Call once first to prevent page blank
 ​
         setInterval(time, 1000);//Turn on the timer
 ​
         function time() {
             var nowTime = new Date();//Returns the total number of milliseconds for the current time
             var times = (inputTime - nowTime) / 1000;//Returns the total number of seconds remaining
             
             var d = parseInt(times / 60 / 60 / 24);//Returns the number of days remaining
             if (d < 10) {
                 d = "0" + d;
             }
             day.innerHTML = d;//Assign the obtained days to the element day
 ​
             var h = parseInt(times / 60 / 60 % 24);//Return remaining hours
             if (h < 10) {
                 h = "0" + h;
             }
             hour.innerHTML = h;//Assign the obtained hour to the element hour
 ​
             var m = parseInt(times / 60 % 60);//Returns the remaining minutes
             if (m < 10) {
                 m = "0" + m;
             }
             minute.innerHTML = m;//Assign the obtained minute to the element minute
 ​
             var s = parseInt(times % 60);//Returns the number of seconds remaining
             if (s < 10) {
                 s = "0" + s;
             }
             second.innerHTML = s;//Assign the obtained seconds to the element second
         }
     </script>

Stop Timer

window.clearInterval(intervalID);

The clearInterval() method cancels the timer that was previously invoked by setInterval().

be careful:

1.window can be omitted

2. The parameter inside is the identifier of the timer

Case: send SMS countdown

  After clicking the button, the button cannot be clicked again within 60 seconds to prevent repeated sending of short messages.

Example:

 
phone number: <input type="number"> <button>send out</button>
     <script>
         var btn = document.querySelector('button');
         // Global variable that defines the number of seconds left
         var time = 3;
         // Register click events
         btn.addEventListener('click', function () {
             // Disable button
             btn.disabled = true;
             // Turn on the timer
             var timer = setInterval(function () {
                 // Judge seconds remaining
                 if (time == 0) {
                     // Clear timer and reset button
                     clearInterval(timer);
                     btn.disabled = false;
                     btn.innerHTML = 'send out';
                 } else {
                     btn.innerHTML = 'Remaining' + time + 'second';
                     time--;
                 }
             }, 1000);
         });
     </script>

(2). location object

What is a location object

The window object provides us with the location property, which is used to obtain or set the URL of the form, and can be used to resolve the URL. Because this property returns an object, we also call this property location object.

URL

Uniform resource locator is the address of standard resources on the Internet. Every file on the Internet has a unique URL, which contains information indicating the location of the file and how the browser should handle it

The general syntax format of URL is:

 protocol://host[:port]/path[/?query]#fragment
 http://www.itcast.cn/index.html?name=andy&age=18#link
formexplain
protocolCommon communication protocols include http,ftp,maito, etc
hostHost (domain name)
portThe port number is optional. If omitted, the default port of the method scheme is used. For example, the default port of http is 80
pathA string whose path is separated by zero or more '/' symbols. It is generally used to represent a directory or file address on the host
queryParameters are separated by the & symbol in the form of key value pairs
fragmentThe content # after the clip is common in link anchors

Properties of the location object

location object propertiesReturn value
location.herfGets or sets the entire URL
location.hostReturn host (domain name)
location.portReturns the port number. If it is not written, it returns an empty string
location.pathnameReturn path
location.searchReturn parameters
location.hashReturning the content # after the clip is common in link anchors

href and search are the key points

Case: 5-minute automatic jump page

Idea: 1. Use the timer to do the countdown effect. 2

2. When the time is up, jump to the page. Use location.href

 <button>click</button>
     <div></div>
     <script>
         var btn = document.querySelector('button');
         var div = document.querySelector('div');
         btn.addEventListener('click', function () {
             // console.log(location.href);
             location.href = 'http://www.itcast.cn';
         })
         var timer = 5;
         setInterval(function () {
             if (timer == 0) {
                 location.href = 'http://www.itcast.cn';
             } else {
                 div.innerHTML = 'You will be' + timer + 'Jump to the home page in seconds';
                 timer--;
             }
         }, 1000);
     </script>

3, JS execution mechanism

What is the result of the execution of the following code?

 
<script> 
 console.log(1);
  
  setTimeout(function () {
      console.log(3);
  }, 1000);
  
  console.log(2);
 </script>

What is the result of the execution of the following code?

 
 <script>
  console.log(1);
  
  setTimeout(function () {
      console.log(3);
  }, 0);
  
  console.log(2);
  </script>

3.1 JS is single threaded

A major feature of JavaScript language is single thread, that is, you can only do one thing at a time

  Single thread means that all tasks need to be queued, and the next task will be executed only after the previous task is completed.

3.2 synchronous and asynchronous tasks

synchronization

  Execute the next task after the previous task is completed. The execution order of the program is consistent and synchronized with the arrangement order of the tasks.

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

asynchronous

  When you do something, because it will take a long time, you can deal with other things while doing it

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 setInerval, seTimeout, etc

Asynchronous task related callback functions are added to the task queue (also known as message queue)

3.3 JS execution mechanism (event loop)

1. Execute the synchronization task in the stack first

2. Put the asynchronous task (callback function) into the task queue

3. Once all 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 and enter the execution stack to start execution

Because the main thread repeatedly obtains, executes, re obtains and re executes tasks, this mechanism is called (event loop)

3.4 cases

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

Tags: Javascript Front-end html Visual Studio Code

Posted on Sat, 20 Nov 2021 22:21:27 -0500 by richardk1