


Usage of when setTimeout() and setInterval() are called and executed in JS_Basic knowledge
Definition
setTimeout() and setInterval() are often used to handle delayed and scheduled tasks. The setTimeout() method is used to call a function or calculated expression after a specified number of milliseconds, while setInterval() can call a function or expression in a loop every specified number of milliseconds until clearInterval clears it.
From the definition, we can see that the two functions are very similar, except that the former is executed once, while the latter can be executed multiple times. The parameters of the two functions are also the same. The first parameter is the code or handle to be executed. The second parameter is the code or handle to be executed. Two are the number of milliseconds of delay.
Very simple definition and easy to use, but sometimes our code is not called at the exact time we imagined, which is very confusing
Simple example
Look at a simple example. After loading a simple page for two seconds, write Delayed alert!
setTimeout('document.write("Delayed alert!");', 2000);
It looks reasonable, let’s take a look Examples of setInterVal() method
var num = 0;
var i = setInterval(function() {
num ;
var date = new Date();
document.write(date.getMinutes() ':' date.getSeconds() ': ' date.getMilliseconds() '
');
The current time (minutes: seconds: milliseconds) is recorded every 1 second. After recording ten times, it is cleared and no longer recorded. Considering that the code execution time may not record the execution time, but the time interval should be the same, look at the results
Copy code
:43:186
:44:200
:45:214
:46:228
:47:242
:48:256
Why
The time interval is almost 1000 milliseconds, but it is not precise. Why is this? The reason is that we have a misunderstanding about JavaScript timers. JavaScript actually runs in a single-threaded environment, which means that the timer only plans the code to be executed at a certain time in the future, and the specific execution time cannot be guaranteed. Because during the life cycle of the page, other code may be controlling the JavaScript process at different times. After the page is downloaded, the code running, event handler, and Ajax callback function all use the same thread. In fact, the browser is responsible for sorting and assigning the priority of a certain program to run at a certain point in time.
Copy the code
function test() {
for (var i = 0; i var div = document.createElement('div');
div.setAttribute ('id', 'testDiv');
document.body.appendChild(div);
document.body.removeChild(div);
}
}
setInterval(test, 10 );
var num = 0;
var I = SetInterval (function () {
Num;
var date = new date (); ':' date.getSeconds() ':' date.getMilliseconds() '
');
We have added another scheduled task to see the results
:19:143
:22:631
:25:888
:28:712
:32:381
:34:146
:35:565
:37:406
The effect is obvious now, the gap is even smaller It's over 3 seconds, and the gap is very inconsistent.
We can think of JavaScript as running on a timeline. When the page loads, the first thing to be executed is the method and variable declaration and data processing to be used later in the page life cycle. After that, the JavaScript process will wait for more code to be executed. When the process is idle, the next piece of code will be triggered
In addition to the main JavaScript process, a queue of code is also needed to be executed the next time the process is idle. As the page life cycle goes by, code will be added to the queue in order of execution. For example, when a button is pressed, its event handler will be added to the queue and executed at the next possible time. When an Ajax response is received, the callback function code is added to the queue. No code in JavaScript is executed immediately, but as soon as the process is idle. The way a timer works on a queue is that code is inserted when a specific time has elapsed, this doesn't mean it will execute right away, it just means it will execute as soon as possible.
After knowing this, we can understand that if we want precise time control, we cannot rely on JavaScript's setTimeout function.
Repeating timer
The timer created using setInterval() can make the code execute in a loop. When the specified effect is achieved, just clear the interval, as in the following example
But the problem with this method is that the timer code may not be executed before the code is added to the queue again. As a result, the judgment conditions in the loop are inaccurate and the code is executed several times without pauses in between. However, JavaScript has solved this problem. When using setInterval(), the timer code is only inserted into the queue when there is no other code instance of the timer. This ensures that the minimum time interval for the timer code to be added to the queue is the specified interval.
Such a rule brings two problems
1.1. Some intervals will be skipped
2.2. The interval between code executions of multiple timers may be smaller than expected
In order to avoid these two shortcomings, we can use setTimeout() to implement repeated timers
Copy code

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
