2
头图

[JavaScript basics] Js timer (the principle you want to see is also)

Blog description

The information involved in the article comes from the Internet and personal summary, which is intended to summarize personal learning and experience. If there is any infringement, please contact me to delete it, thank you!

illustrate

This chapter is going through the second refurbishment. One year later, when I read my own article, I feel that something needs to be done. It has to be richer! Half a page or a page, I feel a bit sorry for myself. In order to be worthy of myself, I added a principle analysis and case study. Know it and why.

The timer of Js is the basic tool of the front end, and it is often used in daily development and work. There are two front-end timers, one is a one-time timer, and the other is a repetitive timer.

One-time timer setTimeout

standard : call the function or calculation expression after the specified number of milliseconds.

Spoken : Make a piece of code run after a specified time.

grammar
setTimeout(code,millisec,lang)
parameterdescribe
codeRequired. The JavaScript code string to be executed after the function to be called.
millisecRequired. The number of milliseconds to wait before executing the code.
langOptional. The script language can be: JScript \ VBScript \ JavaScript
Case study
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Js的定时器</title>
</head>

<body>

    <p>点击按钮,在等待 3 秒后弹出 "Hello"。</p>
    <button onclick="myFunction()">我是按钮,点我</button>

    <script>
        function myFunction() {
            setTimeout(function () {
                alert("Hello")
            }, 1000 * 3);
        }
    </script>

</body>

</html>

Repetitive timer setInterval

standard : according to the specified cycle (in milliseconds) to call the function or calculation expression. The method will keep calling the function until clearInterval() is called or the window is closed.

Spoken : You can make a piece of code run once every specified time.

grammar
setInterval(code,millisec,lang)
parameterdescribe
codeRequired. The function to be called or the code string to be executed.
millisecmust. The time interval between periodically executing or calling code, in milliseconds.
langOptional. JScript \ VBScript \ JavaScript
Case study
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Js的定时器</title>
</head>

<body>

    <input id="clock" />

    <button onclick="clearDate()">别变了,快停止吧,点我!</button>

    <script type="text/javascript">
        const id = setInterval(() => {
            const date = new Date();
            const time = date.toLocaleTimeString();
            document.getElementById("clock").value = time;
        }, 1000);

        function clearDate() {
            clearInterval(id)
        }
    </script>

</body>
  
</html>
Time error

setInterval specifies the interval between <span style="color: red">start execution</span>, and does not consider the time consumed by each task execution itself. So in fact, the interval between two executions will be less than the specified time.

For example, setInterval specifies that it will be executed every 100ms, and each execution takes 5ms, then the second execution will start 95 milliseconds after the end of the first execution. If a certain execution takes a very long time, such as 105 milliseconds, then after it ends, the next execution will start immediately.

In order to ensure that there is a fixed interval between two executions, you can use setInterval instead of setInterval, but after each execution, use setTimeout to specify the specific time for the next execution.

var i = 1;
var timer = setTimeout(function() {
  alert(i++);
  timer = setTimeout(arguments.callee, 2000);
}, 2000);

Eliminate the timer

When using a timer, you need to have a good habit of clearing the timer, especially for repeating timers, you must clear them in time.

How to clear the timer

Compared with the two methods of creating timers, Js also gives the corresponding clearing methods, which are clearTimeout(obj) and clearInterval(obj) .

After seeing that both methods receive a parameter, this parameter is the identifier of the timer, which is defined to receive the variable of the timer method when the timer is used.

Case study
// 一秒之后打印
const test1 = setTimeout(function(){
   console.log('hello world')
},1000);

// 每秒打印一次
const test2 = setInterval(function(){
    console.log('hello world')
},1000)

// 清理定时器
clearTimeout(test1);
clearInterval(test2)

principle

JavaScript language features

JavaScript is an object-based weakly typed language. As a browser scripting language, its main purpose is to interact with the page and manipulate the DOM.

The important point is that the execution environment of JavaScript is single-threaded, that is, it is loaded synchronously by default, which means that the loading of JavaScript is blocked. JavaScript can only complete one thing at the same time, execute from top to bottom, the following code waits for the above code to be parsed.

In this case, the code behind is actually blocked. Blocking means waiting, and waiting means user experience. Once the user experience comes, it must work hard to find a way, so synchronization and asynchrony have emerged.

Synchronous and asynchronous

Synchronous operation: queue execution.

Asynchronous operation: parallel execution.

Asynchronous tasks have no blocking effect.

Synchronous tasks are executed in the main thread, forming an execution stack. Until the main thread is idle, it will go to the event queue to check whether there are executable asynchronous tasks. If there are any, they will be pushed into the main process.

Asynchronous tasks are implemented asynchronously in JavaScript through callback functions. Back to the topic of this article, once setTimeout() is used, the callback function inside is asynchronous code, but the code inside will not be executed immediately, but wait for the main queue. It is empty and will be executed after the specified delay time is reached.

Operating mechanism

setTimeout and setInterval is to move the specified code out of this execution, wait until the next round of Event Loop, and then check whether the specified time is up. If it arrives, execute the corresponding code; if not, wait until the next round of Event Loop to re-judge.

This means that setTimeout and setInterval must wait until all the synchronization tasks of this round of Event Loop have been executed, and then wait until all tasks of the "task queue" of this round of Event Loop have been executed before they begin to execute. Since it is uncertain how long the previous task will take to complete, there is no way to guarantee the execution within the time.

Case study
setTimeout(function() {
  console.log("异步任务执行");
}, 0);
 
function a(x) {
  console.log("a() 开始运行");
  b(x);
  console.log("a() 结束运行");
}
 
function b(y) {
  console.log("b() 开始运行");
  console.log(y);
  console.log("b() 结束运行");
}
 
console.log("同步任务开始");
a("hello world");
console.log("同步任务结束");
 
// 同步任务开始
// a() 开始运行
// b() 开始运行
// hello world
// b() 结束运行
// a() 结束运行
// 同步任务结束
// 异步任务执行

Summarize

  • The JavaScript engine is single-threaded, and it forces asynchronous events to be queued for execution;
  • The execution principles of setTimeout and setInterval are different, and you need to pay attention to the impact of their execution time;
  • If a one-time timer (setTimeout) is blocked, it will wait until there is a suitable execution time (the waiting time may be longer than the delay time it defines);
  • If the execution time of the repetitive timer (setInterval) callback function is very long (longer than the defined interval time), the interval timer may continue to execute without interval.

thanks

Universal network

novice tutorial

And the hardworking self, personal blog , GitHub test , GitHub

Public Account-Guizimo, Mini Program-Xiaogui Blog


归子莫
1k 声望1.2k 粉丝

信息安全工程师,现职前端工程师的全栈开发,三年全栈经验。