Timing events in JavaScript
In this article, we will shortly learn about the timing events in JavaScript. Sometimes we may like to execute some part of code certain time later. That’s also called ‘Scheduling a call’.
There are two libraries to do the timing events:
setTimeout()
will wait for the number of milliseconds specified, after that allows us to executes the function.setInterval()
will wait for the number of milliseconds specified, after that it will execute the function after every regular interval as specified.
These methods are not a part of JavaScript specification. But most environments have the internal scheduler and provide these methods. In particular, they are supported in all browsers and Node.js.
setTimeout()
Syntax
setTimeout(func|code, [delay], [arg1], [arg2], ...);
Parameter
func|code
A string of code or Function to execute. Usually, that’s a function. For historical reasons, a string of code can be passed, but that’s not recommended.
delay
Number of milliseconds to wait before function execution.
[arg1]
, [arg2]
, … Arguments for the function (not supported in IE9)
function myFunction() { alert("Hello!"); } setTimeout(myFunction, 3000); //This will show the alter with 'Hello!' //after 3 seconds of this method call.
With arguments
function myFunction(name) { alert("Hello", name); } setTimeout(myFunction, 3000, 'Poopcoder!'); //This will show the alter with 'Hello Poopcoder!' //after 3 seconds of this method call.
So we can do like as below also,
setTimeout("alert('Hello')", 1000); //Using arrow function is highly recommended. Like this setTimeout(() => alert('Hello'), 1000);
Cancelling the setTimeOut()
Return value of setTimeOut()
is numerical ID that we can use to cancel the execution.
var timer = setTimeout(() => alert('Hello'), 3000); clearTimeout(timer);
setInterval()
Syntax
setInterval(func|code, [delay], [arg1], [arg2], ...);
All arguments has the same meaning as setTimeout()
. But it executes the function regularly after the specified interval of time.
function myFunction() { setInterval(function(){ alert("Hello"); }, 3000); } //This will show the alter with 'Hello!' for //every 3 seconds of this method call.
To cancel the interval, we can use clearInterval()
var timer = setInterval(myFunction, 3000); clearInterval(timer);
Notes
- 1000 millisecond = 1 sec.
setTimeout
expects a reference to a function. And heremyFunction()
runs the function, and the result of its execution is passed tosetTimeout
. In our case the result ofmyFunction()
isundefined
(the function returns nothing), so nothing is scheduled.- If the first argument is a string, then JavaScript creates a function from it.