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

Simple steps to write custom instructions in Vue3.0

Preface Vue provides a wealth of built-in directi...

React Native JSI implements sample code for RN and native communication

Table of contents What is JSI What is different a...

Correct way to load fonts in Vue.js

Table of contents Declare fonts with font-face co...

Version numbers in css and js links in HTML (refresh cache)

background Search the keyword .htaccess cache in ...

Ten Experiences in Presenting Chinese Web Content

<br /> Focusing on the three aspects of text...

How does MySQL ensure data integrity?

The importance of data consistency and integrity ...

This article will show you how to use SQL CASE WHEN in detail

Table of contents Simple CASEWHEN function: This ...

Implementation of HTML to PDF screenshot saving function

Using Technology itext.jar: Convert byte file inp...

Use javascript to create dynamic QQ registration page

Table of contents 1. Introduction 1. Basic layout...

Usage of mysql timestamp

Preface: Timestamp fields are often used in MySQL...

Detailed explanation of the role of static variables in MySQL

Detailed explanation of the role of static variab...

How to install and connect Navicat in MySQL 8.0.20 and what to pay attention to

Things to note 1. First, you need to create a my....