JavaScript Timer Details

JavaScript Timer Details

1. Brief Introduction

In JavaScript , there are two timers: setInterval() and setTimeout() , and there are methods 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.

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

2. setInterval

2.1 Description

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, ...)


2.2 Parameters

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)

Note: The parameter func|code is usually passed in as a function. For historical reasons, passing in a code string is supported, but is not recommended.

2.3 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.

2.4 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>

3. setTimeout

3.1 Description

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, ...)

3.2 Parameters

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)

Note: The parameter func|code is usually passed in as a function. For historical reasons, passing in a code string is supported, but is not recommended.

3.3 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>

4. Cancel the timer

clearInterval() method cancels timer set by setInterval() .
clearTimeout() method cancels 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: Note that setTimeout() 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.

5. Use timers in the console

You can also use timers in the browser console

console.time(timerName)


Create a timer named name and start it.

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

console.timeEnd(timerName)

Calling console.timeEnd(name ) stops the timer and prints the elapsed time in milliseconds.

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

5.1 Usage

For loop 99999 times how much time example:

console.time(name);

let num;
for (let index = 0; index < 99999; index++) {
  num++;
}

console.timeEnd(name);

This is the end of this article about the details of JavaScript timer. For more relevant JavaScript timer content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

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

<<:  Why Google and Facebook don't use Docker

>>:  Interpreting MySQL client and server protocols

Recommend

How to open the port in Centos7

The default firewall of CentOS7 is not iptables, ...

How to use video.js in vue to play m3u8 format videos

Table of contents 1. Installation 2. Introducing ...

Implementation of installing Docker in win10 environment

1. Enter the Docker official website First, go to...

Detailed explanation of how to install MariaDB 10.2.4 on CentOS7

CentOS 6 and earlier versions provide MySQL serve...

In-depth understanding of the use of r2dbc in MySQL

Introduction MySQL should be a very common databa...

Docker file storage path, modify port mapping operation mode

How to get the container startup command The cont...

MySQL 5.7 installation and configuration tutorial under CentOS7 64 bit

Installation environment: CentOS7 64-bit MINI ver...

A brief analysis of how MySQL implements transaction isolation

Table of contents 1. Introduction 2. RC and RR is...

Deep understanding of the mechanism of CSS background-blend-mode

This article is welcome to be shared and aggregat...

How to set up virtual directories and configure virtual paths in Tomcat 7.0

Tomcat7.0 sets virtual directory (1) Currently, o...