JavaScript setTimeout() and setInterval() tutorial



If you want to call a function after a specific amount of time, just like using a timer, you can call setTimeout() or setInterval() function.

setTimeout() is for single execution, and setInterval() will run repeatedly after we stop it.

Here is two video tutorial about setTimeout() and setInterval() and in the end of this post you can see the source code you see in the video.

Source code:

<!DOCTYPE html>
<html>
	<head>
		<title>zkTutorials</title>
	</head>
	<body>
		<h1>JavaScript setTimeout() and setInterval()</h1>
		<button onclick="timeoutFunction()">setTimeout</button>
		<button onclick="intervalFunction()">setInterval</button>
		<button onclick="stopInterval()">Stop Interval</button>
		<p id="myNumber">MyNumber</p>
		<script>
			function timeoutFunction(){
				var timer = setTimeout(function(){
					alert("Hey!");
				}, 1000);
			}
			
			var interval;
			function intervalFunction(){
				var myNumber = 0;
				interval = setInterval(function(){
					myNumber ++;
					document.getElementById("myNumber").innerHTML = myNumber;
				}, 1000);
			}
			
			function stopInterval(){
				clearInterval(interval);
			}
		</script>
	</body>
</html>
loading...