There are sometimes that we need to execute JavaScript code in time-intervals. These are called Timing Events.
There are two timing events method in Javascript –
These methods are actually not a part of JavaScript language but supported by all browsers and NodeJS.
The syntax is as below –
setTimeout(func, delay[, arg1, arg2..])
Func- h3
Anonymous callback Function to be executed.
Delay- h3
The delay before run, in milliseconds (1000 ms = 1 second).
Arg1, arg2…- h3
Optional Arguments for the function (not supported in IE9-)
Let jump into examples.
The below code will run the function sayJS() after 10 seconds. It will show an alert pop-up after 10 seconds.
function sayJS() { alert('Hello JS'); } setTimeout(sayJS, 10000);
We can also use it with the optional arguments.
function sayJS(lang, role) { alert(lang + ' ' + role); } setTimeout(sayJS, 10000, "JavaScript", "Developer");
The syntax is as below
setInterval(func, delay[, arg1, arg2..])
All arguments have the same meaning as setTimeout. But setInterval runs regularly after the given interval of time.
To stop further calls, we should call clearInterval(timerId). Let’s look at the complete example.
// repeat with the interval of 2 seconds let timerId = setInterval(() => alert('Hello JS'), 2000); // after 10 seconds stop setTimeout(() => { clearInterval(timerId); alert('stoped...'); }, 10000);
Here we are using the arrow function to call the callback function inside only. Also, notice we have to use the setTimeout for clearInterval or else the browser won’t know when to run clearInterval.
I have learned many things from this article. It is beneficial for me. Thank you!
Nice example for beginners.. I m a beginner so this is very helpful for me ... so plz give this type of beginners example..
This is a great introduction to variables in JavaScript! As a beginner to JavaScript, I found this guide very helpful in understanding the basics of variables and how they are used in JavaScript.
Thanks for sharing the information, it is very helpful, I hope to get more such beautiful blogs from you.
You have shared great information with me i appreciate your work!
Build various types of web applications,command-line application,etc....
Introduction: Angular (What is Angular?)Angular was formerly introdu...
Leave a Reply
Your email address will not be published. Required fields are marked *