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

CSS Viewport Units for Fast Layout

CSS Viewport units have been around for the past ...

Example of implementing todo application with Vue

background First of all, I would like to state th...

Summary of uncommon js operation operators

Table of contents 2. Comma operator 3. JavaScript...

How to completely uninstall Docker Toolbox

Docker Toolbox is a solution for installing Docke...

HTML+CSS to achieve charging water drop fusion special effects code

Table of contents Preface: accomplish: Summarize:...

HTML markup language - reference

Click here to return to the 123WORDPRESS.COM HTML ...

mysql 5.6.23 winx64.zip installation detailed tutorial

For detailed documentation on installing the comp...

MySql 8.0.11-Winxp64 (free installation version) configuration tutorial

1. Unzip the zip package to the installation dire...

Detailed explanation of MySQL sql99 syntax inner join and non-equivalent join

#Case: Query employee salary levels SELECT salary...

A comprehensive summary of frequently used statements in MySQL (must read)

The knowledge points summarized below are all fre...

Summary of common problems and application skills in MySQL

Preface In the daily development or maintenance o...

Detailed explanation of Nginx's rewrite module

The rewrite module is the ngx_http_rewrite_module...