Simple JS timer: from setTimeout to setInterval

foreword

When it comes to the most basic concepts of the JavaScript programming language, timers are a must-knowledge point. When writing a website, you often come across situations where you need to execute some code at certain intervals. At this time, JavaScript timers can come in handy.


What is a timer?

JSA timer is a very common JavaScriptprogramming method for periodically executing a specified piece of code. JSTimers can be used to achieve many very practical effects, such as periodically updating page content, dynamically loading data, implementing animation effects, and so on.

JavaScriptIn , there are two main timer methods: setTimeout()and setInterval(). Both methods can be used to periodically execute a specified piece of code, but there are some key differences between them.


setTimeout() creates

setTimeout()A method can also periodically execute a specified code segment, but it will only execute once, and then wait for the specified time to execute again. Simply put, it is to execute a piece of code after a specified time (delayed execution).

setTimeout()There are 4three , only two parameters are used here, the first parameter is an arrow function, and the second parameter indicates how many seconds to execute the arrow function.

let timer = setTimeout(() => {
    
    
    console.log("我将在两秒后输出!");
}, 2 * 1000);

clearTimeout() clears

clearTimeout()The method is used to cancel a scheduled task, provided that the scheduled task has not been triggered yet.

let timer = setTimeout(() => {
    
    
    console.log("我将在两秒后输出!");
}, 2 * 1000);
clearTimeout(timer); //定时任务取消,两秒后将不会有任何输出

setInterval() creates

setInterval()Methods allow us to periodically execute a specified piece of code, and this piece of code will continue to execute. Simply put, it is to execute a piece of code at regular intervals (interval execution).

setInterval()The usage of the parameters of the method is setTimeout()consistent that of , the difference is that this timer will always be executed cyclically.

let timer = setInterval(() => {
    
    
    console.log("每隔一秒我将输出一次")
}, 1000)

console print

insert image description here


setInterval() clear

clearInterval()It is used to cancel the recurring scheduled task.

let timer = setInterval(() => {
    
    
    console.log("每隔一秒我将输出一次")
}, 1000)
setTimeout(() => {
    
    
    clearInterval(timer);// 将在3秒时被清除
}, 3000);

console print

insert image description here


Timers and Recursion

A recursive function is a special kind of function that calls itself to accomplish some task. JavaScriptIn , recursive functions and timers can be used to solve many complex problems.

The following is the simplest chestnut

<template>
  <div>{
   
   {num}}</div>
</template>

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      num: 0,
    };
  },
  mounted() {
      
      
    this.recursion();
  },
  methods: {
      
      
    recursion() {
      
      
      this.num++;
      setTimeout(() => {
      
      
        this.recursion();
      }, 1000);
    },
  },
};
</script>

achieve effect

insert image description here


In-depth understanding

Because JavaScriptthe execution environment of is single-threaded, that is, it is loaded synchronously by default, that is to say, JavaScriptthe loading of is blocked. It can only complete one thing at the same time, execute from top to bottom, the following code waits for the above code to complete parsing. In this case, the following code is actually blocked. Blocking means waiting, and waiting means user experience. Once the user experience comes, you have to work hard to find a way, so synchronization and asynchrony appear.

synchronous and asynchronous

  • Synchronous operation: Queue execution.
  • Asynchronous operations: execute in parallel.

Asynchronous tasks do not have blocking effects. Synchronous tasks are executed in the main thread, forming an execution stack. When the main thread is idle, it will go to the event queue to check whether there are executable asynchronous tasks, and if so, push them into the main process.

Asynchronous JavaScripttasks are asynchronous through callback setTimeout()functions. Once used, the callback function inside is asynchronous code, but the code inside will not be executed immediately, but wait for the main queue to be empty and reach a certain delay time will be executed.

operating mechanism

setTimeout()setInterval()The operation mechanism of and is to move the specified code out of the current execution, and then check whether the specified time has come when the next round of event loop occurs. If it arrives, execute the corresponding code; if not, wait until the next round of event loop to judge again.

This means that the code specified bysetTimeout() and must wait until all the synchronous tasks of the current round of the event loop are executed, and then wait until all the tasks of the "task queue" of the current round of the event loop are executed before starting to execute (macro tasks). setInterval()Since it is uncertain how long it will take for the previous tasks to be executed, there is no way to guarantee that they will be executed within a certain time.

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("同步任务结束");

console print result

insert image description here


Guess you like

Origin blog.csdn.net/Shids_/article/details/130077961