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

Installing the ping tool in a container built by Docker

Because the Base images pulled by Docker, such as...

How to make Python scripts run directly under Ubuntu

Let’s take the translation program as an example....

How to generate Vue user interface by dragging and dropping

Table of contents Preface 1. Technical Principle ...

Introduction to the use and disabling of transparent huge pages in Linux

introduction As computing needs continue to grow,...

Docker solves the problem that the terminal cannot input Chinese

Preface: One day, I built a MySQL service in Dock...

Detailed explanation of Jquery datagrid query

Table of contents Add code to the Tree item; 1. S...

Solution to Vue3.0 error Cannot find module'worker_threads'

I'll record my first attempt at vue3.0. When ...

Node+Express test server performance

Table of contents 1 Test Environment 1.1 Server H...

CocosCreator learning modular script

Cocos Creator modular script Cocos Creator allows...

Linux file management command example analysis [display, view, statistics, etc.]

This article describes the Linux file management ...

How to add configuration options to Discuz! Forum

Discuz! Forum has many configuration options in th...

Table Tag (table) In-depth

<br />Table is a tag that has been used by e...

Does MySql need to commit?

Whether MySQL needs to commit when performing ope...