Delay the Function Execution with JavaScript setTimeout

10/12/2021

Contents

In this article, you will learn how to delay the function execution with JavaScript setTimeout.

What is setTimeout()?

To delay the function execution, you can use the JavaScript setTimeout() method.

The syntax is below.

setTimeout(function, delay);

The “delay” parameter is the time interval in milliseconds.
For example, if you enter 1000 for “delay”, the function will be executed after 1 second.

Demo

A message will be displayed 3 seconds after clicking the button.

Code

HTML

<button type="button" id="btn">Start</button>

JavaScript

const btn = document.getElementById('btn');

function showMsg() {
  alert("Hello!");
}

btn.addEventListener('click', () => {
  setTimeout(showMsg, 3000);
});