How to make a delay in javaScript

This article shows you how to add a delay to your script with JavaScript, including a working example.

Creating a Delay with JavaScript

Sometimes when working with JavaScript, you may need to delay the execution of a certain portion of code. This can be useful in a variety of cases, such as when you need to wait for an asynchronous function to finish before continuing with the rest of the program. Fortunately, JavaScript provides a simple way to do this with the setTimeout() function.

The setTimeout() function takes two parameters: a function to execute, and a delay in milliseconds. When called, it will execute the given function after the specified delay. For example, the following code will print "Hello World!" after a delay of 1000 milliseconds (1 second):

setTimeout(function() {
  console.log("Hello World!");
}, 1000);

The setTimeout() function also returns a value that can be used to cancel the timeout. This value is an integer that represents the ID of the timeout, and it can be passed to the clearTimeout() function to cancel the timeout before it has been executed. For example, the following code will cancel the timeout created in the previous example:

let timeoutID = setTimeout(function() {
  console.log("Hello World!");
}, 1000);

clearTimeout(timeoutID);

The setTimeout() function is a simple and effective way to delay the execution of code in JavaScript. With it, you can easily wait for asynchronous functions to finish before continuing, or simply delay the execution of code for a certain length of time.

Answers (0)