JavaScript Timer Details

  • 2021-12-04 18:08:14
  • OfStack

Directory 1, Brief Introduction 2, setInterval2.1 Description 2.2 Parameter 2.3 Return Value 2.4 Usage 3, setTimeout3.1 Description 3.2 Parameter 3.3 Usage 4, Cancel timer5, Use Timer in Console

1. Brief introduction

In JavaScript There are two timers in setInterval() And setTimeout() There are also methods to cancel the timer.
This is all window You can omit the object of the window . These two methods are not JavaScript In the specification of.

There are four related methods of timer method:

方法 描述
setInterval 周期性地调用1个函数(function)或者执行1段代码。
clearInterval 取消掉用setInterval设置的重复执行动作。
setTimeout 在指定的延迟时间之后调用1个函数或者执行1个代码片段。
clearTimeout 方法可取消由 setTimeout() 方法设置的 timeout。

Note: setTimeout () is executed only once setInterval () is executed periodically at given intervals.

2. setInterval

2.1 Description

setInterval() Method can repeatedly call a function or execute a code snippet at a specified period. The period is in milliseconds.
setInterval() Method if it is not clearInterval() Method closes or the page closes, then 1 will be called straight.
setInterval has multiple parameters.
First, if the first parameter is a code snippet, the setInterval () method can be optionally filled.
Second, if the first argument is a function, the setInterval () method can have multiple arguments.


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


2.2 Parameters

参数 必/选填 描述
func | code 必填 调用的函数后要执行的函数或代码字符串
delay 必填 执行代码前所需的时间,单位为毫秒,可以不填,默认值是 0
arg1,arg2… 选填 要传入被执行函数(或代码字符串)的参数列表(IE9 以下不支持)

Note: Parameter funccode 1 is passed in as a function. For some historical reasons, passing in code strings is supported, but it is not recommended.

2.3 Return value

Return value timeoutID Is a positive integer that represents the number of the timer. This value can be passed to the setInterval() 0 To cancel the timer.

2.4 Usage

This is an example of clicking a button every 1 second, adding a number to 1;


<p id="showNum"></p>
<button onclick="timer()"> Point my number per second plus 1</button>

<script>
  const showNum = document.getElementById("showNum");

  let timerId; //  Timer's ID
  let num = 0;

  function timer() {
    timerId = setInterval(addNum, 1000);
  }

  function addNum() {
    showNum.innerText = `${num++}`;
  }

  //  Stop timer code not written 
</script>

3. setTimeout

3.1 Description

setTimeout() Returns an integer representing the number of the timer, which can be used to cancel the timer later.
setTimeout() Allows us to postpone the execution of the function until after 1 time interval.


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

3.2 Parameters

setTimeout() Parameters here and setInterval() The parameter of is 1.

参数 必/选填 描述
func | code 必填 调用的函数后要执行的函数或代码字符串
delay 必填 执行代码前所需的时间,单位为毫秒,可以不填,默认值是 0
arg1,arg2… 选填 要传入被执行函数(或代码字符串)的参数列表(IE9 以下不支持)

Note: Parameter funccode 1 is passed in as a function. For some historical reasons, passing in code strings is supported, but it is not recommended.

3.3 Usage

setTimeout() Usage and setInterval() It's one kind,

But setTimeout() Execute only once different, setInterval() Is executed periodically according to the specified time.


<p id="showNum"></p>
<button onclick="timer()"> After clicking, wait 1 Number of seconds plus 1</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 timer

clearInterval() Method to cancel the setInterval() Set timer .
clearTimeout() Method to cancel the setTimeout() Set timer .

The usage method is very simple, with only one parameter, and this parameter timeoutID Is the identifier for which you want to cancel the timer.
The ES 136EN is composed of the corresponding setTimeout() Or setInterval() 0 Call returns.


clearInterval(intervalID);
clearTimeout(timeoutID);


Note: Note that setTimeout () and setInterval () share a single number pool, and that clearTimeout () and clearInterval () are technically interchangeable. However, to avoid confusion, do not mix the cancellation timing function.

The usage is simple:


function timer() {
  timerId = setTimeout(addNum, 1000);
}

clearTimeout(timerId); //  When the code runs to this line, it cancels timer The timer that is set. 

5. Use a timer in the console

You can also use a timer in the browser console


console.time(timerName)


Create a timer named name and start timing.

Note: Every one timer must have only one name, and up to 10,000 timers can run simultaneously on the page.

console.timeEnd(timerName)

Call console.timeEnd(name ) Stops the timer and outputs the elapsed time (in milliseconds).


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

5.1 Usage

How many times does for loop 99999 times take? Example:


console.time(name);

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

console.timeEnd(name);

Related articles: