JavaScript - Simple Time Counter
Submitted by razormist on Wednesday, January 8, 2020 - 22:01.
In this tutorial we will create a Simple Time Counter using JavaScript. This code will start a timer that have been set when the user click the start timer button. The code use onclick() function to launch a specific function that will start a timer by calling the setInterval() a built-in javascipt function with a duration of 1000 is equivalent to 1 seconds. You can apply this script to your code to make your transaction faster, it is a user-friendly program feel free to modify it.
We will use JavaScript to add some new feature to the website interface by actually written into an HTML page. It is what gives your page a different interactive elements and animation that engage a user.
There you have it we successfully created a Simple Time Counter using JavaScript. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
Getting Started:
This is the link for the bootstrap that i used for the layout design https://getbootstrap.com/.The Main Interface
This code contains the interface of the application. To create this just write these block of code inside the text editor and save this as index.html.- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
- <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
- </head>
- <body>
- <nav class="navbar navbar-default">
- <div class="container-fluid">
- </nav>
- <div class="col-md-6 well">
- <hr style="border-top:1px dotted #ccc;"/>
- <div class="col-md-4">
- <div class="form-group">
- <input type="number" id="count" class="form-control"/>
- </div>
- </div>
- <div class="col-md-8">
- </div>
- </div>
- </body>
- </html>
Creating the Script
This code contains the script of the application. This code will start a timer when the button is clicked. To do this just copy and write these block of codes as shown below inside the text editor and save it as script.js inside the js directory- function startTimer(btn){
- var count=document.getElementById("count").value;
- if(count==0){
- alert("Please enter a valid number!");
- }else{
- document.getElementById("count").value=""
- btn.setAttribute('disabled', 'disabled');
- var counter = setInterval(function(){
- count = count - 1;
- if (count == -1) {
- clearInterval(counter);
- btn.removeAttribute("disabled");
- return;
- }
- var seconds = count % 60;
- var minutes = Math.floor(count / 60);
- var hours = Math.floor(minutes / 60);
- minutes %= 60;
- hours %= 60;
- document.getElementById("result").innerHTML = "<span class='text-primary'>"+hours+"</span>" + "hours " + "<span class='text-primary'>"+minutes+"</span>" + "minutes and " + "<span class='text-primary'>"+seconds+"</span>" + "seconds";
- }, 1000);
- }
- }
Add new comment
- 279 views