1//single event i.e. alarm, time in milliseconds
2var timeout = setTimeout(function(){yourFunction()},10000);
3//repeated events, gap in milliseconds
4var interval = setInterval(function(){yourFunction()},1000);
1var count = 0;
2 function updateCount() {
3 count = count + 1;
4 document.getElementById("number").innerHTML = count;
5 setTimeout(updateCount, 1000);
6 }
1<!DOCTYPE HTML>
2<html>
3<head>
4<meta name="viewport" content="width=device-width, initial-scale=1">
5<style>
6p {
7 text-align: center;
8 font-size: 60px;
9 margin-top: 0px;
10}
11</style>
12</head>
13<body>
14
15<p id="demo"></p>
16
17<script>
18// Set the date we're counting down to
19var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();
20
21// Update the count down every 1 second
22var x = setInterval(function() {
23
24 // Get today's date and time
25 var now = new Date().getTime();
26
27 // Find the distance between now and the count down date
28 var distance = countDownDate - now;
29
30 // Time calculations for days, hours, minutes and seconds
31 var days = Math.floor(distance / (1000 * 60 * 60 * 24));
32 var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
33 var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
34 var seconds = Math.floor((distance % (1000 * 60)) / 1000);
35
36 // Output the result in an element with id="demo"
37 document.getElementById("demo").innerHTML = days + "d " + hours + "h "
38 + minutes + "m " + seconds + "s ";
39
40 // If the count down is over, write some text
41 if (distance < 0) {
42 clearInterval(x);
43 document.getElementById("demo").innerHTML = "EXPIRED";
44 }
45}, 1000);
46</script>
47
48</body>
49</html>
50
1var countDownDate = new Date("Jul 25, 2021 16:37:52").getTime();
2
3var myfunc = setInterval(function() {
4 var now = new Date().getTime();
5 var timeleft = countDownDate - now;
6
7 var days = Math.floor(timeleft / (1000 * 60 * 60 * 24));
8 var hours = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
9 var minutes = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
10 var seconds = Math.floor((timeleft % (1000 * 60)) / 1000);
11
12 }, 1000)
1// this example takes 2 seconds to run
2const start = Date.now();
3
4// After a certain amount of time, run this to see how much time passed.
5const milliseconds = Date.now() - start;
6
7console.log('Seconds passed = ' + millis / 1000);
8// Seconds passed = *Time passed*
1Timers are used to execute a piece of code at a set time or also to repeat the code in a given interval of time.
2This is done by using the functions
31. setTimeout
42. setInterval
53. clearInterval
6
7The setTimeout(function, delay) function is used to start a timer that calls a particular function after the mentioned delay.
8The setInterval(function, delay) function is used to repeatedly execute the given function in the mentioned delay and only halts when cancelled.
9The clearInterval(id) function instructs the timer to stop.