


When creating a new Promise object, we can pass in two callback functions as arguments. For example, if you have ever worked with an API call and made a request to the server, that request returns a "pending" Promise that will ultimately become "resolved" or "rejected". In Javascript, a Promise object represents the eventual completion of an action. setTimeout allows us to wait a specified amount of time before invoking a new callback function with setInterval operating similarly except the delay will reset and continue repeating.įor the purposes of slowing down operation for something like a while loop, neither of these are directly helpful since they delay the invocation of a new action rather than the delay the original function in which they were called. For example, Ruby has sleep(1000) and Python has time.sleep(1) to "pause" operation for 1 second, but there is no direct correlate in Javascript.Īsynchronous actions in Javascript can usually call upon one of these two functions. Most program languages have a sleep function/method that can be invoked to delay the next operation in a function. How do I slow down the operation speed of a function to the point where I could create visual models and allow the viewer time to process them before it updated to the next step? I had planned to create a second entry in that series this week, however I ran into an obstacle:

Therefore, the above sleep() method will only suspend the execution of the function where you'll call it.In my last blog entry, I had created a visualizer to model an approach to solving a Leetcode algorithm problem. Remember that due to the asynchronous nature of JavaScript, it is not possible to stop the entire program execution. But after the introduction of promises in ES6, we can easily implement such a feature in JavaScript to make a function sleep: const sleep = ( ms ) => timer ( ) // Start time -> T08:42:34.754Z // After 2s -> T08:42:36.763Z // After 4s -> T08:42:38.764Z

However, this functionality is not available in JavaScript due to its asynchronous execution model. Similarly, PHP has sleep(2), and Python has time.sleep(2) to make the program stops for 2 seconds. For example, in Java, you can use the Thread.sleep(2 * 1000) to halt the current thread execution for 2 seconds. Many programming languages provide a sleep() function that pauses the execution of the code for a certain amount of time.
