Timer
timer allows us to execute javascript functions after a specified period or at specific time and can also synchronize multiple events in a particular time span.
Various methods that allows us to use timer
timer allows us to execute javascript functions after a specified period or at specific time and can also synchronize multiple events in a particular time span.
Various methods that allows us to use timer
- setTimeout() - executes code at specified interval. Syntax : setTimeout(function,delaytime) function defines the method that the timer calls and the delaytime specifies the number of milliseconds to wait before calling the method.
- clearTimeout() - deactivates the timer that is set using the setTimeout() method. Syntax : clearTimeout(timer)
- setInterval() - executes function after a specified time interval. Syntax : setInterval(function, intervalTime). function parameter specifies the method to be called and intervalTime parameters specifies the time interval between the function calls.
- clearInterval() - deactivates the timer that is set using the setInterval() method. Syntax : clearInterval(timer)
Example 1
<!DOCTYPE html>
<html>
<head>
<title>javaScript setTimeout() method</title>
</head>
<body>
<h1>JavaScript setTimeout() method</h1>
<script>
function func_setTimeout() {
var time = setTimeout("alert('2 seconds')", 2000);
}
</script>
<form>
<input type="button" value="setTimeout() alert" onclick="func_setTimeout()" />
</form>
</body>
</html>
Example 2: function will be called again and again in case of setInterval() method
<!DOCTYPE html>
<html>
<head>
<title>javaScript setInterval() method</title>
</head>
<body>
<h1>JavaScript setInterval() method</h1>
<script>
function func_setTimeout() {
var time = setInterval("alert('2 seconds')", 2000);
}
</script>
<form>
<input type="button" value="setInterval() alert" onclick="func_setTimeout()" />
</form>
</body>
</html>