js implements multithreading based on setTimeout and setInterval

  • 2021-06-28 11:20:25
  • OfStack

This article provides an example of how js implements multithreading based on setTimeout and setInterval.Share it for your reference, as follows:

javascript cannot implement thread blocking (sleep) because sleep involves system calls.js does not allow system calls for security reasons.

If 1 is sure to continue executing the statement, CPU can only be consumed by the method of while(1) idle, so break is the time to judge.However, this method is not really sleep.

Timer that executes only once

// Timer runs asynchronously 
function hello(){
// Execute method using method name 
var t1 = window.setTimeout(hello,1000);
var t2 = window.setTimeout("hello()",3000);// Execute method using string 
window.clearTimeout(t1);// Remove timer 

Duplicate timer

function hello(){
// Repeat a method 
var t1 = window.setInterval(hello,1000);
var t2 = window.setInterval("hello()",3000);
// Method of removing timer 


If there are two methods in a page that are executed after the page is loaded, but the actual results cannot be executed in the order you imagine, what can you do?


You can add a timer to the onload method, set a timer, and delay it for a period of time before running, so that you can artificially distinguish the order in which the page loading methods run.

More readers interested in JavaScript-related content can view this site's topics: Summary of JavaScript Switching Effects and Techniques, Summary of JavaScript Finding Algorithmic Techniques, Summary of JavaScript Animation Effects and Techniques, Summary of JavaScript Errors and Debugging Techniques, Summary of JavaScript Data Structure and Algorithmic Techniques.Summary of JavaScript Traversal Algorithms and Techniques and Summary of JavaScript Mathematical Operation Usage

I hope that the description in this paper will be helpful to everyone's JavaScript program design.

Related articles: