JavaScript timing events

preview_player
Показать описание
Link for all dot net and sql server video tutorial playlists

Link for slides, code samples and text version of the video

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.

In JavaScript a piece of code can be executed at specified time interval. For example, you can call a specific JavaScript function every 1 second. This concept in JavaScript is called timing events.

The global window object has the following 2 methods that allow us to execute a piece of JavaScript code at specified time intervals.

setInterval(func, delay) - Executes a specified function, repeatedly at specified time interval. This method has 2 parameters. The func parameter specifies the name of the function to execute. The delay parameter specifies the time in milliseconds to wait before calling the specified function.

setTimeout(func, delay) - Executes a specified function, after waiting a specified number of milliseconds. This method has 2 parameters. The func parameter specifies the name of the function to execute. The delay parameter specifies the time in milliseconds to wait before calling the specified function. The actual wait time (delay) may be longer.

Let's understand timing events in JavaScript with an example. The following code displays current date and time in the div tag.

[div id="timeDiv" ][/div]
[script type="text/javascript"]
function getCurrentDateTime() {
}

getCurrentDateTime();
[/script]

At the moment the time is static. To make the time on the page dynamic modify the script as shown below. Notice that the time is now updated every second. In this example, we are using setInterval() method and calling getCurrentDateTime() function every 1000 milli-seconds.

[div id="timeDiv" ][/div]
[script type="text/javascript"]
setInterval(getCurrentDateTime, 1000);

function getCurrentDateTime() {
}
[/script]

clearInterval(intervalID) - Cancels the repeated execution of the method that was set up using setInterval() method. intervalID is the identifier of the repeated action you want to cancel. This ID is returned from setInterval() method. The following example demonstrates the use of clearInterval() method.

Starting and stopping the clock with button click : In this example, setInterval() method returns the intervalId which is then passed to clearInterval() method. When you click the "Start Clock" button the clock is updated with new time every second, and when you click "Stop Clock" button it stops the clock.

[div id="timeDiv" ][/div]
[br /]
[input type="button" value="Start Clock" onclick="startClock()" /]
[input type="button" value="Stop Clock" onclick="stopClock()" /]
[script type="text/javascript"]
var intervalId;

function startClock() {
intervalId = setInterval(getCurrentDateTime, 1000);
}

function stopClock() {
clearInterval(intervalId);
}

function getCurrentDateTime() {
}

getCurrentDateTime();
[/script]

Now let's look at example of using setTimeout() and clearTimeout() functions. The syntax and usage of these 2 functions is very similar to setInterval() and clearInterval().

Countdown timer example : When we click "Start Timer" button, the value 10 displayed in the textbox must start counting down. When click "Stop Timer" the countdown should stop. When you click "Start Timer" again, it should start counting down from where it stopped and when it reaches ZERO, it should display done in the textbox and function should return.

[input type="text" value="10" id="txtBox" /]
[br /][br /]
[input type="button" value="Start Timer" onclick="startTimer('txtBox')" /]
[input type="button" value="Stop Timer" onclick="stopTimer()" /]
[script type="text/javascript"]
var intervalId;

function startTimer(controlId)
{
seconds = seconds - 1;
if (seconds == 0)
{
return;
}
else
{
}

intervalId = setTimeout(function () { startTimer('txtBox'); }, 1000);
}

function stopTimer()
{
clearTimeout(intervalId);
}
[/script]
Рекомендации по теме
Комментарии
Автор

I was also confused as to why the startTimer function call had to be wrapped in an anonymous function in the setTimeout parameter. This is the explanation I found on Google which explains it quite well...

setTimeout accepts a function as an argument and the correct way to pass a function as an argument is either defining it as an anonymous function or just providing the function name. If you use parenthesis (brackets) you aren't actually passing a function, you are executing the function and passing the result of the funciton to setTimeout. Hence, when specifying a function in setTimeout and anywhere else you need to pass a function as an argument you should not use parenthesis.

So, because the startTimer function has a parameter that needs to be passed the whole thing has to be wrapped in an anonymous function in order to be passed to setTimeout.

roberthall
Автор

one small piece of advice, put the functions names as tags in your video titles, when I searched the keywords of functions I couldn't find yours. This will increase the chance you be found. btw, ur teaching is very good

girlandhercomputer
Автор

Thank u so much sir..keep continue venkat sir

mageshwarank
Автор

I don't understand what element this refers to: In chrome devtools it says "controlId" is undefined. Where is this element?

charlesloehle
Автор

I get NaN when click start if the countdown has already reach 0 (Done). How to ensure that when user click start a second time after the countdown reach zero display a nice message or restart the countdown process again?

emmanuelmbwambo
Автор

How did you run the timer using the SetTImeout ? It should run only once right ?

kttalkZ
Автор

What is difference between setInterval and SetTimeout also when should is use over what

sureshrajput
Автор

so the startTimer function is calling itself every 1 second. wouldn't this create many layers of recursion if the timer is is set very high?

trumankwong
Автор

is there a way that i can make the second program making use of setInterval and clearInterval?
Please Help!

emm__jayy
Автор

At 13:15 - can someone explain the strange construct? Why the anonymous function that calls startTimer? Also, would there be a way not to hard-code txtBox?

raphaelb.
Автор

Is it mandatory to mention -- function() { startTimer('txtBox');}
in the setTimeOut ?
Why does -- setTimeout(startTimer('txtBox'), 1000);
not work?

kasper
Автор

what if you want to do a countdown with minutes and seconds?

Susanamorato
Автор

I'm confused by the function "getCurrentDateTime" and everything in it. Why do I need all of that stuff?

thavrisco
Автор

hi venkat,
can you please upload callbacks and promisses in javascript.

gkh
Автор

Sir why you used Anonymous function for setTimeout() ? 
why it doesn't work like this  startTimer("txtbox");  ? 

I am waiting for reply thanks.

TheMRTIMBUK
Автор

Thnax sir, sir please upload video on reporting crystal +  jquery 

shahnawazatharkazmi