Smart Ways to Wait in JavaScript

RustcodeWeb
2 min readAug 15, 2024

--

Photo by Artem Sapegin on Unsplash

Waiting or delaying code execution in JavaScript is essential for handling asynchronous operations, animations, and timed events. JavaScript provides several methods for introducing delays or waiting periods in code. This article explores different ways to wait in JavaScript and provides examples for each approach.

01. Using setTimeout()

The setTimeout() function allows you to execute a piece of code after a specified delay. The delay is defined in milliseconds.

  • setTimeout() is used to delay the execution of a function by 2000 milliseconds.
  • The message “This message is shown after a 2-second delay” appears after a 2-second pause.

02. Using setInterval()

The setInterval() function repeatedly executes a piece of code at specified intervals. The delay is defined in milliseconds, and the code runs continuously until clearInterval() is called.

  • setInterval() is used to execute the code every 1000 milliseconds.
  • The interval is cleared after 5 executions using clearInterval().

Support Our Work: BuyMeACoffee

Originally published at https://www.rustcodeweb.com on August 15, 2024.

--

--

No responses yet