How does the JavaScript function setTimeout work?The JavaScript function setTimeout's syntax is as follow: setTimeout('action', milliseconds)
The action parameter can be any JavaScript function or method call. Milliseconds indicates the time period. Thus, for setTimeout, the action will be performed once after the specified number of milliseconds. Here is an example of setTimeout:
setTimeout('alert(\'This is JavaScript setTimeout in action\')', 2000);
The alert message will be shown once after 2000 milliseconds, i.e. once after 2 seconds. |
How does the JavaScript function setInterval work?The JavaScript function setInterval's syntax is as follow:
setInterval(action, milliseconds)
Action can be any JavaScript function or method call. Milliseconds indicates the time period. Thus, the specified action will be performed continuously every time the number of milliseconds elapses.
Here is an example of setInterval:
setInterval('alert(\'This is JavaScript setInterval in action\')', 2000);
The alert message will be shown every 2000 milliseconds, i.e. every 2 seconds, continuously. |
How do I stop the action started by setTimeout or setInterval?A reference to the setTimeout or setInterval can be obtained. When doing a setTimeout a reference to the JavaScript setTimeout can be obtained as follow: var mytimeout = setTimeout('alert(\'JavaScript setTimeout\')', 8000); JavaScript setTimeout is then cleared as follow: clearTimeout(mytimeout); When doing a setInterval a reference to the JavaScript setInterval can be obtained as follow:
var myinterval = setInterval('alert(\'JavaScript setInterval\')', 8000); JavaScript setInterval is then cleared as follow: clearInterval(myinterval); |
How do I use setTimeout to also repeat actions in the same manner as setInterval?For example, suppose you have a setInterval call as follow: setInterval('alert(\'This is JavaScript setInterval in action\')', 3000); The same can be achieved by using setTimeout. First add an initial call for setTimeout: setTimeout('repeattimeout()', 3000); Then, inside the repeattimeout() function, call the setTimeout again: function repeattimeout() {
alert('This is JavaScript setInterval in action, sort of!');
setTimeout('repeattimeout()', 3000);
} |
Show me JavaScript setInterval in action?Have a look at this implementation of a JavaScript clock. |