Detailed explanation of the JavaScript timer principle

Detailed explanation of the JavaScript timer principle

Preface:

In many pages, we can see some countdown or time-related effects. Today, Xiao Xiong will give an overview of the countdown in JavaScript.
First, let's take a look at the timer. In JS, there are two types of timers:

1. setTimeout() timer

grammar:

window.setTimeout(call function, [delay in milliseconds]);

setTimeout() method is used to set a timer that executes the called function after the timer expires.
For example: write a page that pops up "Hello" after five seconds.

The code is as follows:

window.setTimeout(function(){
            alert('Hello');
        },5000);

The running results are:

It should be noted that:

  • window can be omitted.
  • This function call can be written directly as a function, or as a function name or as a string 'function name()'.
  • The delay in milliseconds defaults to 0 if omitted; if given, it must be in milliseconds. The calling function of setTimeout() is also called callback function. Ordinary functions are called directly in the order of code. This function requires a waiting time, and it will be called only when the time is up, so it is called a callback function.

2. Stop the setTimeout() timer

Once we have created a timer, what should we do if we want to cancel it? The function to clear the timer is used as follows:

window.clearTimeout(timeoutID)

clearTimeout() method cancels a timer previously established by calling setTimeout() .
Here window can be omitted, and the parameter is the identifier of the timer.

For example:

In the above case, if we want to stop it before the specified event, we can first add a click button and add an event to clear the timer to this button. The operation is:

  var hello = window.setTimeout(function(){
            alert('Hello');
        },5000);
        var btn = document.querySelector('button');
        btn.addEventListener('click',function(){
            window.clearTimeout(hello);
        })

The running effect is:

It can be seen that when we do not click the stop button, 'Hello' pops up after five seconds. After refreshing the page, when we click the button, no matter how long it takes, there will be no pop-up window, and the timer is cleared successfully.

3. setInterval() timer

Let's look at another type of timer.

window.setInterval(callback function, [interval in milliseconds]);

setInterval() method repeatedly calls a function, calling the callback function once every this time.

  • window can be omitted.
  • The calling function can be written directly as a function, or as a function name or as a string 'function name()'.
  • If the number of milliseconds is omitted, the default value is 0. If it is written, it must be milliseconds, indicating that this function will be automatically called every certain number of milliseconds.
  • We often assign an identifier to a timer.
  • The first execution is also executed after the interval of milliseconds, and then it is executed every milliseconds.

For example:

Let's write a timer to print 'hello' every second. The code is:

  setInterval(function(){
            console.log('Hello')
        },1000);

The running effect is:

4. Clear the setInterval() timer

Similarly, we can also clear the effect of the setInterval() timer. The syntax is:

window.clearInterval(intervalID);

clearInterval() method cancels a timer previously established by calling setInterval() .

Notice:

  • window can be omitted.
  • The parameter inside is the identifier of the timer.

For example, we now have two buttons. Clicking one can start the timer, and clicking the other can clear the timer. The operation method is:

<body>
    <button class='begin'>Start</button>
    <button class='stop'>Stop</button>
    <script>
        var btn = document.querySelectorAll('button');
        var timer = null;
        btn[0].addEventListener('click',function(){
            timer = setInterval(function(){
                console.log('Hello');
            },1000)
        })
        btn[1].addEventListener('click',function(){
            clearInterval(timer)
        })
</script>
</body>

The running effect is:

5. Electronic clock case

We can now make an electronic clock that displays the current year, month, day, hour, minute, and second, and allows them to change automatically. The code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 500px;
            margin: 100px auto;
            font-size: 25px;
        }
    </style>
</head>
<body>
    <div></div>
    <script>
        var div = document.querySelector('div');
        function showTime(){
            var date = new Date();
            var y = date.getFullYear();
            var m = date.getMonth()+1;
            m = m>=10?m:'0'+m;
            var d = date.getDate();
            d = d>=10?d:'0'+d;
            var h = date.getHours();
            h = h>=10?h:'0'+h;
            var dm = date.getMinutes();
            dm = dm>=10?dm:'0'+dm;
            var ds = date.getSeconds();
            ds = ds>=10?ds:'0'+ds;
            var str = y+'year'+m+'month'+d+'day'+h+'hour'+dm+'minute'+ds+'second';
            div.innerHTML = str;
            setTimeout(showTime,1000);
        }
        window.onload = showTime();
    </script>
</body>
</html>

The running effect is:

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

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

<<:  Sample code for programmatically processing CSS styles

>>:  HTML discount price calculation implementation principle and script code

Recommend

How to implement the @person function through Vue

This article uses vue, and adds mouse click event...

Vue button permission control introduction

Table of contents 1. Steps 1. Define buttom permi...

MySQL subqueries and grouped queries

Table of contents Overview Subqueries Subquery Cl...

Detailed explanation of the use of HTML header tags

HTML consists of two parts: head and body ** The ...

Solution to the problem that Java cannot connect to MySQL 8.0

This article shares a collection of Java problems...

A brief discussion on the synchronization solution between MySQL and redis cache

Table of contents 1. Solution 1 (UDF) Demo Case 2...

JS implements the dragging and placeholder functions of elements

This blog post is about a difficulty encountered ...

Detailed explanation of the API in Vue.js that is easy to overlook

Table of contents nextTick v-model syntax sugar ....

TypeScript interface definition case tutorial

The role of the interface: Interface, in English:...

5 tips for writing CSS to make your style more standardized

1. Arrange CSS in alphabetical order Not in alphab...

Summary of some tips on MySQL index knowledge

Table of contents 1. Basic knowledge of indexing ...

This article takes you into the world of js data types and data structures

Table of contents 1. What is dynamic typing? 2. D...

Browser compatibility summary of common CSS properties (recommended)

Why do we need to summarize the browser compatibi...