- Creating a timer with JavaScript
- Demo
- Youtube
- Thanks for reading!
- Как сделать таймер на JavaScript
- Подготовка:
- Таймер на JavaScript:
- Вывод:
- Timer in JavaScript
- Examples to Implements Timer in JavaScript
- 1. window.setTimeout(argument1, argument2,argument3,….)
- 2. window.setInterval(argument1,argument2,argument3,….)
- Using Arguments for Called Function
- Conclusion
- Recommended Articles
Creating a timer with JavaScript
Here we have the start , pause and reset functions, in the start function, we start the setInterval every 10 milliseconds (because every 1 millisecond locks depending on the browser). In the pause function we clear the setInterval , in the start function it is necessary to clear before starting so that we don’t have several working in the background, so before starting the procedures, the pause function is called. In the reset function, we reset our auxiliary variables and so that the text on the screen returns to 0(zero) on the screen, we set it manually using the innerText .
function timer() if ((millisecond += 10) == 1000) millisecond = 0; second++; > if (second == 60) second = 0; minute++; > if (minute == 60) minute = 0; hour++; > document.getElementById('hour').innerText = returnData(hour); document.getElementById('minute').innerText = returnData(minute); document.getElementById('second').innerText = returnData(second); document.getElementById('millisecond').innerText = returnData(millisecond); > function returnData(input) return input > 10 ? input : `0$input>` >
- If the millisecond added to 10 is equal to 1000, then a second has passed and then we reset the millisecond and increase it by 1 second.
- If the second is equal to 60, then a minute has passed and then we reset the second to 1 minute.
- If the minute is 60, then an hour has passed and then we reset the minute and increase it by one hour.
Finally we print on the screen using innerText .
The returnData function is used only to make the text more dynamic on the screen, making the following logic, if the digit is less than 10 then concatenates with a 0(zero) in front.
Demo
See the complete project working below.
Youtube
If you prefer to watch, I see the development on youtube (video in PT-BR).
Thanks for reading!
If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!
Как сделать таймер на JavaScript
В этой статье вы узнаете как сделать простой таймер на js (JavaScript), если вы новичок и давно хотите сделать счётчик времени, то вам однозначно надо посмотреть эту статью.
Также надо сказать, что подобную статью уже ест на нашем сайте, но там мы делали отсчёт времени до определённой даты (Смотреть здесь), тут же мы реализуем простой таймере.
Подготовка:
Для начала подготовим HTML файл в котором у нас будет форма, куда будем вписывать сколько минут надо отсчитать, и кнопка запуска, также блок куда будет выводится сколько осталось времени.
Объяснять не чего не буду, так как, тут всё должно быть понятно.
Таймер на JavaScript:
Теперь сделаем код таймера на JS, это программа очень простая, думаю вы быстро всё поймёте.
Сначала берём строку или форму куда будем вписывать сколько минут надо отсчитать, дальше кнопка для запуска и блок для вывода таймера.
Теперь перейдём к основному коду.
Тут мы просто берём при нажатие кнопки данные из формы и преобразуем в числовой тип данных, так как, в форме хранится строчка. Умножаем это значение на 60, потому что нам нужны минуты.
Давайте разберём этот код, сначала мы запускаем таймер и в нём же получаем сколько секунд, минут и часов осталось.
Потом идёт условие, если переменная которая отвечает за время значение равно или меньше нуля, то программа выключается и выводит сообщение о том, что время закончилось.
Иначе будет создаётся строчка в которую подставляется значение переменных созданных выше, также можете заметить, что используется функция Math.trunc() , оно используется, потому что мы делим число, но при деление может получится число с плавающей точкой, а эта функция её округляет.
Подставляем полученную строку в объект для вывода таймера, на этом всё.
Вывод:
Как видите программа не сложная, мы сделали простой таймер на JavaScript, надеюсь вам понравилась статья.
Timer in JavaScript
The window object provides us with the timer functions that we can use in javascript. Basically, these functions are implemented by browser itself. Their implementation can vary from browser to browser. As these functions have global scope, we can access and use them in our JavaScript’s tag. The two main functions provided by window object to control the timing of execution of events are as window.setTimeout() and window.setInterval(). Both of them can be used without specifying window and return an id of the timer which they create.
Web development, programming languages, Software testing & others
Examples to Implements Timer in JavaScript
Below are the examples mentioned:
1. window.setTimeout(argument1, argument2,argument3,….)
where argument1 stands for reference of the function to be executed, argument2 for time period in milliseconds after which you want to execute the function and argument3 and so on exists as an option parameters you want to pass to function reference of argument1.
SetTimeout() function allows you to execute a specific functionality after some time period. For example, if you want to print a message saying “Hi! You are here to learn timers in JavaScript.” after 5 seconds of clicking the button named “Purpose”. In this case, you can write a function alerting the message and use setTimeout function to call it after 5 seconds on click of the button named “Purpose”. Here’s how your code will look somewhat like this-
Click "Purpose"to know what brings you here.
function knowPurpose()
Code: After running the code.
Code: After 5 seconds of clicking the button output seen will be as shown
Explanation: clearTimeout() function is used to stop the event from occuring. You can use it by calling it with the id returned from setTimeout() function. For example in the above case if id returned of the timer is stored in variable name timeouteId and you call the clearTimeout(timeouteId) before 5 seconds then the message haven’t be displayed.
2. window.setInterval(argument1,argument2,argument3,….)
where argument1 stands for reference of the function to be executed, argument2 for the time period in milliseconds after which you want to repetitively execute the function and argument3 and so on exists as an optional parameter you want to pass to function reference of argument1.
When you want to execute certain functionality repetitively after particular time period then you can use setInterval function to do so. Suppose you want to display a digital clock and stop it when you click “Stop” button. Then you can use the setInterval method to call the getTime function repetitively after 1 second so that the time displayed will be updated. Here’s how you can write the code-
Click "Stop" to stop the displayed time over here.
var timerId= setInterval(()=>< getTime() >,1000); function getTime() < var currentDate= new Date(); var currentTime= currentDate.toLocaleTimeString(); document.getElementById("displayTime").innerHTML = currentTime; >function stopTime()
Explanation: clearInterval() function is used to stop the event from occurring. You can use it by calling it with the id returned from setInterval() function.As soon as you will click the stop button it will stop displaying the updated time and will display the time when you clicked the button.
Output: The output of the above program will be as follows-
Now suppose you want to update the message saying “10 Seconds Left!”,“9 Seconds Left!”,… and so on and display “Yes! You have done it!”. How can we implement it? Here’s where we can make the use of setInterval() function. Let’s write the code for it.
Explanation: The message will show the countdown and will display “Yes! You have done it!” after ten seconds. In the middle of countdown if you press “Stop It” button then the timer will stop and message displayed will also stop displaying the message which was getting seen at that particular instance when you pressed the button and will not be modified further.
Using Arguments for Called Function
Now suppose in a real-time situation, there’s comes a necessity to pass a parameter to the function which is being called. For example, You want to display a message after 3 seconds of clicking the submit button and the message should display the name passed to that function. In this case, you will use setTimeOut() function as the message is to be displayed only once after some time and not repetitively. Now you will use setTimeOut() function with more than two arguments to it. We can use the third argument to specify the name to be displayed in the message and passed to the function and create the message accordingly. Code for the same will be as follows-
setTimeout(isBest,3000, 'Javascript'); function isBest(what)
Output: Of the above code will be an alert message displaying “Javascript is the best.” after 3 seconds.
So now you know how to pass arguments to the setTimeout() function. Similar is the working of setInterval() function.
As we discussed earlier, all these timer functions are called by window object which is , in turn, an object of HTML DOM(Document Object Model). Let’s check this with the help of an example. In javascript, if you want to know about the current object then “this” keyword is used to represent it.
setTimeout(whoIsCalling,1000); function whoIsCalling()
Conclusion
We can conclude that setTimeout() function is called by Window object of HTML Dom. You can try this for other functions too and verify it for yourself.setTimeout() and setInterval() functions are extensively used when you want to schedule an event after some predefined period and depending on whether you want to call the event once or repetitively you can make choice from both of them.clearTimeout() and clearInterval() functions are used to stop and clear the timer which is set by setTimeout() and setInterval() functions respectively.
Recommended Articles
This is a guide to Timer in JavaScript. Here we discuss the introduction to Timer in JavaScript with examples with called function. You can also go through our other suggested articles to learn more –
500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access
1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access
1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access
3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access
All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access
Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access