Users Online

· Guests Online: 90

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Timer in JavaScript

Timer in JavaScript

Timer in JavaScript

Introduction to 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 <script> 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.

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-

Code:

<!DOCTYPE html>
<html>
<body>
<p>Click "Purpose"to know what brings you here.</p>
<button onclick="setTimeout(knowPurpose(), 5000);">Purpose</button>
<script>
function knowPurpose() {
alert('Hi! You are here to learn timers in Javascript.');
}
</script>
</body>
</html>

Code: After running the code.

After running

Code: After 5 seconds of clicking the button output seen will be as shown

After 5 seconds

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-

Code:

<!DOCTYPE html>
<html>
<body>
<p id="displayTime"></p>
<p>Click "Stop" to stop the displayed time over here.</p>
<button onclick="stopTime()">Stop</button>
<script>
var timerId= setInterval(()=>{
getTime()
},1000);
function getTime(){
var currentDate= new Date();
var currentTime= currentDate.toLocaleTimeString();
document.getElementById("displayTime").innerHTML = currentTime;
}
function stopTime(){
clearInterval(timerId);
}
</script>
</body>
</html>

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-

After 5 seconds

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.

Code:

<!DOCTYPE html>
<html>
<body>
<button onclick="clearInterval(progressBarId)">Stop it</button>
<p id="progressBar"></p>
<script>
var waitingCount=10; //Initialize counter
var progressBarId = setInterval(displayProgress ,1000);
function displayProgress() {
document.getElementById("progressBar").innerHTML = waitingCount + " Seconds Left!";
waitingCount -=1; //decrement counter
if(waitingCount===0)
document.getElementById("progressBar").innerHTML = "Yes! You have done it!";
clearInterval(progressBarId); //Display the final message and clear the timer
}
}
</script>
</body>
</html>

Output:

Timer in JavaScript - 4

Timer in JavaScript - 5

Timer in JavaScript - 6

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-

Code:

<!DOCTYPE html>
<html>
<body>
<script>
setTimeout(isBest,3000, 'Javascript');
function isBest(what) {
alert(what+" is the Best.");
}
</script>
</body>
</html>

Output: Of the above code will be an alert message displaying “Javascript is the best.” after 3 seconds.

Timer in JavaScript - 7

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.

Code:

<!DOCTYPE html>
<html>
<body>
<script>
setTimeout(whoIsCalling,1000);
function whoIsCalling() {
alert(this+" is the calling you.");
}
</script>
</body>
</html>

Output:

Timer in JavaScript - 8

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.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.95 seconds
10,826,698 unique visits