Home » JavaScript Tutorial

JavaScript | Timer

Here, we are going to learn about the Timer in JavaScript, we will also learn about the setInterval() function with examples in JavaScript.
Submitted by Siddhant Verma, on March 06, 2020

In this article, we'll build a simple timer using JavaScript. First, we'll understand the date object and how we can utilize the date object to get minutes and seconds, then we'll look briefly at the setInterval() asynchronous function and finally we'll combine all our knowledge to create a simple timer.

The Date Object represents a different data type in JavaScript and as the name suggests is used to store and hold a value having a 'Date' type. This date could be anything from a few years ago, to the current date or the date a few years from now as long as it is a valid date. We can create a new date object using the Date() constructor function.

const now = new Date();
console.log(now);

Output

Tue Jan 07 2020 17:07:51 GMT+0530 (India Standard Time)

We have declared a new Date object now using the Date() constructor. This is similar to the way we create Booleans using the "new" keyword. The Date() constructor takes in as parameter the date to be created and must be entered in the same format as it is displayed. Since we kept it empty, we got back the current timestamp, i.e. the exact date at which the now date object is created.

const then = new Date('Jan 01 2020 17:07:51 GMT+0530 (India Standard Time)');
console.log(then);

Output

Wed Jan 01 2020 17:07:51 GMT+0530 (India Standard Time)

then represents the date of the specified day that we passed inside the Date() constructor as a parameter. The getMinutes() and getSeconds() are methods that can be used on the Date object to get the total minutes and seconds for that date object.

console.log(then.getMinutes() + ' minutes past ' + then);
console.log(now.getMinutes() + ' minutes past ' + now);
console.log(then.getSeconds() + ' seconds past ' + then);
console.log(now.getSeconds() + ' seconds past ' + now);

Output

7 minutes past Wed Jan 01 2020 17:07:51 GMT+0530 (India Standard Time)
7 minutes past Tue Jan 07 2020 17:07:51 GMT+0530 (India Standard Time)
51 seconds past Wed Jan 01 2020 17:07:51 GMT+0530 (India Standard Time)
51 seconds past Tue Jan 07 2020 17:07:51 GMT+0530 (India Standard Time)

The setInterval() function is an asynchronous function that invokes a callback after every specified amount in milliseconds.

setInterval(function() {
    console.log('Every 2s ');
}, 2000);

Output

(2) Every 2s 

Now that we have all the knowledge that we need, let's go ahead and build our JavaScript Timer.

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Focus method</title>
    <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

    <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

</head>
<style>
    body {
        background: coral;
    }
</style>

<body>
    <div class="container">
        <h3 class="center">JavaScript Timer</h3>
        <h5 class="from">From: </h5>
        <h5>Minutes elapsed: 
        <span class="min"></span>
      </h5>
        <h5>Seconds elapsed: 
        <span class="sec"></span>
      </h5>
    </div>
</body>
<script>
</script>

</html>

Output

JS Time (1)

We'll first create a date object for a specified date and get a reference to that.

const year2020=new Date('Jan 07 2020 17:47:00');
document.querySelector('.from').textContent+=year2020;

Output

JS Time (2)

Great! Now we'll fire a setInterval() function which will run every 1 second or a 1000 milliseconds and inside that function, we'll display the minutes and seconds elapsed from the earlier date object we created by subtracting its minutes from the current date object's minutes. We'll do the same to get the seconds elapsed.

<script>
    const year2020=new Date('Jan 07 2020 17:47:00');
    document.querySelector('.from').textContent+=year2020;
    setInterval(function(){
      let now=new Date();
      document.querySelector('.min').textContent=now.getMinutes()-year2020.getMinutes();
      document.querySelector('.sec').textContent=now.getSeconds()-year2020.getSeconds();

    },1000)
     
</script>

Output

JS Time (3)

And you can see that the timer updates the seconds and minutes elapsed dynamically!






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.