Detailed explanation of JavaScript timers

Detailed explanation of JavaScript timers

Brief Introduction

In JavaScript, there are two timers: setInterval() and setTimeout(), each of which has a method to cancel the timer.

These are all window objects, and window can be omitted when calling. These two methods are not in the JavaScript specification.

There are four timer method related methods.

method describe
setInterval Periodically call a function or execute a section of code.
clearInterval Cancel the repetitive action set with setInterval.
setTimeout Calls a function or executes a code snippet after a specified delay.
clearTimeout Method can cancel the timeout set by the setTimeout() method.

The difference between setTimeout() and setInterval() is that they execute at different times.

Note: setTimeout() is executed only once, while setInterval() is executed periodically at a given interval.

setInterval

describe

setInterval() method can repeatedly call a function or execute a code segment according to a specified period. The period unit is milliseconds.

If setInterval() method is not closed by clearInterval() method or the page is closed, it will continue to be called.

There are multiple parameters for setInterval.

First, if the first parameter is a code segment, then the setInterval() method is optional.

Second, if the first parameter is a function, the setInterval() method can have multiple parameters.

let timerId = setInterval(func|code, delay, arg1, arg2, ...)

parameter

parameter Required/Optional describe
func | code Required Function or code string to be executed after the called function
delay Required The time required before executing the code, in milliseconds, can be left blank, the default value is 0
arg1, arg2... Optional The parameter list to be passed into the executed function (or code string) (not supported by IE9 and below)

The parameter func|code usually passes in functions. For historical reasons, passing in a code string is supported, but is not recommended.

Return Value

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

usage

This is an example of clicking a button and incrementing a number every second;

<p id="showNum"></p>
<button onclick="timer()">Click me to increase the number by one every second</button>
 <script>
  const showNum = document.getElementById("showNum");
   let timerId; // Timer ID
  let num = 0;
   function timer() {
    timerId = setInterval(addNum, 1000);
  }
   function addNum() {
    showNum.innerText = `${num++}`;
  }
   // No code to stop the timer is written</script>

setTimeout

describe

setTimeout() returns an integer representing the timer number, which can be used to cancel the timer later.

setTimeout() allows us to defer the execution of a function until a certain interval has passed.

let timerId = setTimeout(func|code, delay, arg1, arg2, ...)

parameter

The parameters of setTimeout() are the same as those of setInterval() .

parameter Required/Optional describe
func | code Required Function or code string to be executed after the called function
delay Required The time required before executing the code, in milliseconds, can be left blank, the default value is 0
arg1, arg2... Optional The parameter list to be passed into the executed function (or code string) (not supported by IE9 and below)

The parameter func|code usually passes in functions. For historical reasons, passing in a code string is supported, but is not recommended.

usage:

The usage of setTimeout() is the same as setInterval() .
However, unlike setTimeout() which is executed only once, setInterval() is executed periodically according to the specified time.

<p id="showNum"></p>
<button onclick="timer()">After clicking, wait for one second and the number increases by one</button>
 <script>
  const showNum = document.getElementById("showNum");
   let timerId;
  let num = 0;
  addNum();
   function timer() {
    timerId = setTimeout(addNum, 1000);
  }
   function addNum() {
    showNum.innerText = `${num++}`;
  }
 </script>

Cancel timer

The clearInterval() method cancels the timer set by setInterval().

The clearTimeout() method cancels the timer set by setTimeout().

The usage is very simple, with only one parameter, which is timeoutID, the identifier of the timer you want to cancel.
This ID is returned by the corresponding setTimeout() or clearTimeout() call.

clearInterval(intervalID);
clearTimeout(timeoutID);

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

Usage is simple

function timer() {
  timerId = setTimeout(addNum, 1000);
}
 clearTimeout(timerId); // When the code runs to this line, the timer set by timer will be canceled.

Using the timer in the console

You can also use timers in the browser console

console.time(timerName)

Create a timer named name and start it.

Each timer must have a unique name, and a maximum of 10,000 timers can run simultaneously on a page.

console.timeEnd(timerName)

Call console.timeEnd(name) to stop the timer and print the elapsed time in milliseconds.

console.time(timerName);
console.timeEnd(timerName);

usage

Example of how long it takes for a for loop to repeat 99999 times.

console.time(name);
 let num;
for (let index = 0; index < 99999; index++) {
  num++;
}
 console.timeEnd(name);

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of the JavaScript timer principle
  • JavaScript Timer Details
  • JavaScript timer to achieve limited time flash sale function
  • JavaScript timer to achieve seamless scrolling of pictures
  • Summary of JavaScript Timer Types

<<:  Several methods of implementing two fixed columns and one adaptive column in CSS

>>:  Several reasons for not compressing HTML

Recommend

A brief discussion on several ways to implement front-end JS sandbox

Table of contents Preface iframe implements sandb...

Implementation steps of encapsulating components based on React

Table of contents Preface How does antd encapsula...

How to compile and install PHP and Nginx in Ubuntu environment

This article describes how to compile and install...

IE6 space bug fix method

Look at the code: Copy code The code is as follows...

How to reduce the root directory of XFS partition format in Linux

Table of contents Preface System environment Curr...

How to install the latest version of docker using deepin apt command

Step 1: Add Ubuntu source Switch to root su root ...

Use of Linux ln command

1. Command Introduction The ln command is used to...

Detailed explanation of Nodejs array queue and forEach application

This article mainly records the problems and solu...

Detailed discussion of several methods for deduplicating JavaScript arrays

Table of contents 1. Set Deduplication 2. Double ...

Zookeeper unauthorized access test problem

Table of contents Preface Detect Zookeeper servic...

Solve the error during connect exception in Docker

When you first start using Docker, you will inevi...

How to automatically execute SQL statements when MySQL in Docker starts

When creating a MySQL container with Docker, some...

Tutorial on installing MySQL on Alibaba Cloud Centos 7.5

It seems that the mysql-sever file for installing...