I am small and live in Wuhan, do two years of new media, ready to use 6 months time to switch to the front end of the industry.

Lesson Objective for today

Yesterday, I mainly learned BOM Window object to control window movement and size change based on search. Today, I mainly started to learn single-thread model and timer based on search. It is another day for learning


Today’s Lesson summary

  • Single threaded mode
  • window.setTimeout()
  • window.clearTimeout()
  • window.setInterval()
  • window.clearInterval()

Single threaded model

Basic instructions

The single-threaded model means that JavaScript runs on only one thread. That is, JavaScript can only perform one task at a time, and all other tasks must queue up later.


Single-threaded runs with engine threads

Note that just because JavaScript runs on a single thread does not mean that the JavaScript engine has only one thread.

In fact, JavaScript engines have multiple threads, and a single script can only run on one thread (called the main thread), with the other threads cooperating in the background.


Historical reasons

The reason JavaScript is single-threaded, rather than multi-threaded, is a matter of history. JavaScript has been single-threaded since its inception because it doesn’t want to complicate the browser.

Because multiple threads need to share resources and potentially modify each other’s results, this is too complicated for a web scripting language.

If JavaScript has two threads at the same time, one thread adds content to the web DOM node, and the other thread removes the node, which thread should the browser use? Should there be a locking mechanism?

So, to avoid complexity, JavaScript was originally single-threaded, which has become a core feature of the language and will not change in the future.


benefits

The advantage of this mode is that the implementation is relatively simple, the execution environment is relatively simple;

The single-threaded model, while limiting JavaScript, gives it advantages that other languages don’t.

When used well, JavaScript programs don’t clog, which is why Node can handle heavy traffic with very few resources.

In order to make use of the computing power of multi-core CPU, HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads, but the child threads are completely controlled by the main thread and cannot operate DOM. So, this new standard doesn’t change the single-threaded nature of JavaScript.


The bad

The disadvantage is that as long as one task takes a long time, subsequent tasks must wait in line, which will delay the execution of the entire program.

A common browser non-response (suspended animation) is usually the result of a single piece of JavaScript code running for so long (such as an infinite loop) that the entire page gets stuck in one place and no other task can be performed.

The JavaScript language itself is not slow, but slow in reading and writing external data, such as waiting for Ajax requests to return results. At this point, if the server does not respond, or the network is not smooth, the script will be stalled for a long time.

If the queue is due to a large amount of computation, the CPU is too busy, but many times the CPU is idle because IO operations (input and output) are slow (such as Ajax operations reading data from the network) and have to wait for the results to come out before executing.

The designers of the JavaScript language realized that the CPU could simply suspend the pending task and run the next one, regardless of the IO operation.

Wait until the IO operation returns the result, then go back and continue the pending task. This mechanism is the “Event Loop” mechanism used in JavaScript.


window.setTimeout()

Basic grammar

var timeoutID = scope.setTimeout(function[, delay.arg1.arg2. ] );var timeoutID = scope.setTimeout(function[, delay]); 
var timeoutID = scope.setTimeout(code[, delay]);
Copy the code

Parameters that

  • Function function is the function you want to execute after the due time (delay milliseconds).

  • code

This is an optional syntax that allows you to compile and execute strings after milliseconds of delay using strings instead of functions (this syntax is not recommended for the same security reasons as eval()).

  • Delay Number of milliseconds after which the function will be called (one second equals 1000 milliseconds). If this parameter is omitted, delay takes the default value 0, which means “immediately” or as soon as possible. In either case, the actual delay may be longer than the expected value. See the reason why the actual delay is longer than the set value: Minimum delay time.

  • arg1, … ArgN optional additional arguments that are passed to function as arguments once the timer expires


The return value

The returned value timeoutID is a positive integer, indicating the timer number. This value can be passed to clearTimeout() to cancel the timer.

Note that setTimeout() and setInterval() share the same number pool, and clearTimeout() and clearInterval() are technically interchangeable. However, to avoid confusion, do not mix the cancel timing functions.

On the same object (a window or worker), setTimeout() or setInterval() will not reuse the same timer number in subsequent calls. But different objects use separate number pools.


Detailed instructions

WindowOrWorkerGlobalScope mixed setTimeout () method set a timer, and execute a function within the timer in the timer expires or the designated a piece of code.


case

The following example sets up two simple buttons in a web page to trigger the setTimeout() and clearTimeout() methods: Press the first button to set a timer, which will display a warning dialog box after 2s and save the timer ID of setTimeout. Press the second button to cancel the timer.

<p>Live Example</p>
<button onclick="delayedAlert();">Show an alert box after two seconds</button>
<p></p>
<button onclick="clearAlert();">Cancel alert before it happens</button>

Copy the code
var timeoutID;

function delayedAlert() {
  timeoutID = window.setTimeout(slowAlert, 2000);
}
 function slowAlert() {  alert('That was really slow! '); }  function clearAlert() {  window.clearTimeout(timeoutID); } Copy the code

Is really waiting for two seconds or so, just appeared a popup ~~~~~


window.clearTimeout()

Basic grammar

scope.clearTimeout(timeoutID)
Copy the code

Parameters that

  • timeoutID

The timer identifier to cancel. This ID is returned by the corresponding setTimeout() call.

It’s worth noting that setTimeout() and setInterval() use a shared ID pool, which means you can technically alternate clearTimeout() and clearInterval(). However, for the sake of clarity, you should avoid doing this.


Detailed instructions

WindowOrWorkerGlobalScope built-in clearTimeout () method to cancel the previous by calling the setTimeout () set up timer.


case

Run the following script on a web page and click the page once. A second later you’ll see a message pop up. If you keep clicking on the page for a second, the popup will no longer appear.

var alarm = {
  remind: function(aMessage) {
    alert(aMessage);
    delete this.timeoutID;
  },
  setup: function() {  this.cancel();  var self = this;  this.timeoutID = window.setTimeout(function(msg) {self.remind(msg); },1000."Wake up!");  },   cancel: function() {  if(typeof this.timeoutID == "number") {  window.clearTimeout(this.timeoutID);  delete this.timeoutID;  }  } }; window.onclick = function() { alarm.setup() }; Copy the code

Wow, this works


window.setInterval()

Basic grammar

varintervalID = scope.setInterval(func, delay, [arg1, arg2, ...] );var intervalID = scope.setInterval(code, delay);
Copy the code

Parameters that

  • Function function is the function you want to execute after the due time (delay milliseconds).

  • code

This is an optional syntax that allows you to compile and execute strings after milliseconds of delay using strings instead of functions (this syntax is not recommended for the same security reasons as eval()).

  • Delay Number of milliseconds after which the function will be called (one second equals 1000 milliseconds). If this parameter is omitted, delay takes the default value 0, which means “immediately” or as soon as possible. In either case, the actual delay may be longer than the expected value. See the reason why the actual delay is longer than the set value: Minimum delay time.

  • arg1, … ArgN optional additional arguments that are passed to function as arguments once the timer expires


The return value

The returned value timeoutID is a positive integer, indicating the timer number. This value can be passed to clearInterval() to cancel the timer.

Note that setTimeout() and setInterval() share the same number pool, and clearTimeout() and clearInterval() are technically interchangeable. However, to avoid confusion, do not mix the cancel timing functions.

On the same object (a window or worker), setTimeout() or setInterval() will not reuse the same timer number in subsequent calls. But different objects use separate number pools.


Detailed instructions

WindowOrWorkerGlobalScope setInterval () method calls a function or to perform a code block, has the fixed time delay between each call.

The setInterval() method provided on the Window and Worker interfaces repeatedly calls a function or executes a code segment with a fixed time delay between calls.

It returns an interval ID that uniquely identifies the interval, so it can be removed later by calling clearInterval(). This method by WindowOrWorkerGlobalScope mixin definition.


case

var intervalID = window.setInterval(myCallback, 500.'Parameter 1'.'Parameter 2');

function myCallback(a, b)
{
 // Your code here
 // Parameters are purely optional.  console.log(a);  console.log(b); } Copy the code


window.clearInterval()

Basic grammar

scope.clearInterval(intervalID)
Copy the code

Parameters that

  • intervalID

ID of the timer to cancel. Is returned by setInterval().

It is worth noting that setInterval() and setTimeout() share their defined IDs, meaning that either clearInterval() or clearTimeout() can be used. However, in order to make your code more readable, you should try to avoid this usage.


Detailed instructions

WindowOrWorkerGlobalScope mixin clearInterval () method can be cancelled by previous setInterval () sets the repetitive tasks regularly.

Usually used with setInterval() is ~~~~


Summary of today’s lesson



Today the mood

Today the main basic understanding of the single thread model and timer related to basic learning, feel very cool, but in the thread and task this little understanding, I hope to learn more tomorrow ~~~~


This article is formatted using MDNICE