Skip to content

JavaScript run function after a delay | Simple example code

  • by

Use setTimeout() inbuilt function to run function after a delay in JavaScript. It’s plain JavaScript, this will call your_func once, after fixed seconds (time).

setTimeout(function() { your_func(); }, 5000);

5000 = 5 sec

If a function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)

JavaScript run function after a delay Example code

HTML example code: Function will call after 1 minute.

<!DOCTYPE html>
<html>
<body>
	<button onclick="timeFunction()">Click Here</button>

	<script>
		function timeFunction() {
			setTimeout(function(){ alert(" 1 seconds! Alert"); }, 1000);
		}
	</script>

	<p>Wait for 1 seconds after click...</p>
</body>
</html>

Output:

How do I delay a function call for 5 seconds?

A setTimeout is a native JavaScript function, which calls a function or executes a code snippet after a specified delay (in milliseconds).

A setTimeout accepts a reference to a function as the first argument. Alert messages will pop up after 5 seconds automatically.

<!DOCTYPE html>
<html>
<body>
	
	<script>
		function greet(){
			alert('Hello wrold!');
		}
		setTimeout(greet, 2000);

	</script>

</body>
</html>

Output:

JavaScript delay a function call for 5 seconds

How to delay a JavaScript function call using JavaScript?

Answer: To delay a function call, use setTimeout() function. function-name − The function name for the function to be executed.

This might be useful to display a popup after a visitor has been browsing your page for a certain amount of time.

setTimeout(function() { functionName() },5000)

Do comment if you have any doubts and suggestions on this JS function-based question and examples program.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading