Is it possible to utilize setTimeout to demonstrate the execution of a while loop visually?

I am working on a function that generates random numbers between 1 and 6 until it matches a target value of 3. I want to create a visual effect where each randomly generated number is displayed on the page, but I'm facing some challenges with delays. Even though I assign the generated number to a paragraph element during each iteration, when I use setTimeout to introduce a delay, the target value shows up immediately without any delay. Is there a way for me to add a delay between each iteration of the loop so that the generated numbers are displayed on the screen one by one?

<body>
  <p id="output"></p>
  <button onclick="myFunction()">Go</button>

  <script>
    function myFunction() 
    {
      var value = 0;
      var target = 3;

      while (value != target)
      {
        value = Math.floor((Math.random() * 6) + 1);
        setTimeout(function() {
          writeOutput(value);
        }, 200);
      }
    }

    function writeOutput(value)
    {
      document.getElementById("output").innerHTML = value;
    }
  </script>
</body>

Answer №1

Finding it quite simple with the utilization of async/await. When inserting await inside a while-loop, the loop halts until the promise resolves.

Let's take a look at this handy sleep function I've made that delivers a promise which resolves after the specified number of milliseconds. The loop will then wait for that duration before continuing.

Check out some introductory resources on async/await here: https://javascript.info/async-await

async function myFunction() 
{
  var value = 0;
  var target = 3;

  while (value != target)
  {
    value = Math.floor((Math.random() * 6) + 1);
    writeOutput(value)
    await sleep(500)
  }
}

function writeOutput(value)
{
  document.getElementById("output").innerHTML = value;
}

function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms)
  })
}
<p id="output"></p>
<button onclick="myFunction()">Go</button>

Answer №2

setTimeout will return immediately, so it is best to call it from within another setTimeout function. An example of this can be seen below.

function myNewFunction() {
  var goal = 4;
  var result = document.getElementById("result");

  function verifyOutcome() {
    var value = Math.round((Math.random() * 6) + 1);
    displayResult(value);
    if (value !== target)
      setTimeout(verifyOutcome, 200);
  }

  function displayResult(value) {
    result.innerHTML = value;
  }
  setTimeout(verifyOutcome, 200);
}
<p id="result"></p>
<button onclick="myNewFunction()">Start!</button>

Answer №3

If you're looking for a more efficient approach, consider eliminating the need for a loop by checking the value only once and then setting up a timeout to repeat the function if necessary. This may not align with your original intention, but it can be a viable solution. Interestingly, there are ways to incorporate delays in JavaScript like this one - Exploring the JavaScript equivalent of sleep()

function displayResult(value)
{
    document.getElementById("result").innerHTML = value;
}

function performTask() 
{
    var value = Math.floor((Math.random() * 6) + 1);
    var target = 3;
    displayResult(value);
  
    if (value !== target)
        setTimeout(performTask, 200);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging the power of Angular to send the contents of a div via email

I have a div element with a specific class name and I am currently exploring ways to extract the rendered components of that div as text in order to include it in the body of an email. I have tried various methods such as using classes and ng-model, but so ...

How come running `npm install <folder>` results in installing different dependencies compared to `npm install lib`?

My current project, project1, relies on <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5221262b3e37367f313d3f223d3c373c262112667c6">[email protected]</a>. When attempting to integrate project2 into project1 as a ...

Loading Ajax content into div (Wordpress) without pre-loading the font can cause display issues

Currently, I'm implementing a JavaScript function within Wordpress using Ajax to load the content of a post into a modal div when specific elements are clicked. Here is an example of how the JS function appears: function openProjectModal($that) { ...

After the component has been initialized for the second time, the elementId is found to be null

When working with a component that involves drawing a canvas chart, I encountered an issue. Upon initializing the component for the first time, everything works fine. However, if I navigate away from the component and return to it later, document.getElemen ...

retrieving the selected checkbox value

My challenge is to extract the values of dynamically changing checked checkBoxes on my webpage. For example: while ($row=myqli_fetch_array($result)){ echo"<div>"; echo"<select id=\"course\" onchange=getCheckBox()> <opt ...

Optimize Material-UI input fields to occupy the entire toolbar

I'm having trouble getting the material-ui app bar example to work as I want. I've created a CodeSandbox example based on the Material-UI website. My Goal: My goal is to make the search field expand fully to the right side of the app bar, regar ...

Rxjs: accessing the most recent value emitted by an observable

As shown in the demo and indicated by the title const { combineLatest, interval, of } = rxjs; const { first, last, sample, take, withLatestFrom } = rxjs.operators; const numbers = interval(1000); const takeFourNumbers = numbers.pipe(take(4)); takeFourNu ...

Jquery not functioning properly for show and hide feature

I'm new to using Jquery and JqueryUI. I have a div named front, which I want to initially display on window load and then hide it by sliding after a delay of 5500 milliseconds. However, I'm encountering errors in the jquery.min.js file. The HTML ...

How can I use JavaScript to consistently fetch the CSS-defined percentage setting for padding/margin instead of the pixel size?

How can I retrieve the padding set in CSS for a div with {padding:10% 10px 20% 10px;} using JavaScript, considering that window.getComputedStyle(myelement).getPropertyValue('padding'); returns different results? In Firefox, it shows as "10% 10px ...

Invoking a prototype method executes the incorrect function repeatedly

I'm currently diving into the world of structures and anonymous functions in JavaScript, and after examining various codes and libraries that implement this technique, I decided to give it a shot. However, when attempting to replicate the method they ...

Experiencing trouble with detecting intersections using the Three.js raycaster

After successfully writing a code to intersect some objects, I encountered an issue when adding a canvas along with other div elements in the HTML document. Now, there seems to be no intersection on the object. You can observe this live example here. If yo ...

retrieving attribute values from JSON objects using JavaScript

I am struggling to extract certain attribute values from a JSON output and use them as input for a function in JavaScript. I need assistance with this task! Below is the JSON data that I want to work with, specifically aiming to extract the filename valu ...

Ajax causing unreliable posts

I am facing an issue with sending and receiving data in my mobile application. I currently use the jquery $.post function, but it seems to be quite unreliable. Issue: Occasionally, about 1 out of 10 times, the POST request is sent successfully, but the ca ...

Tips for avoiding a crash when trying to access a non-existent key using an ordinal number

The output of the code snippet below is "Cat" and undefined. *When a key does not exist in an object, the result will be "undefined". var animals = {"mammals": ["Cat", "Dog", "Cow"]}; var groupA = animals.mammals[0]; var groupB = animals.birds; console.log ...

I am sending an AJAX request to a remote server in order to retrieve access records

Currently, I am attempting to retrieve data by sending an ajax request to a remote server controller from my current remote page. Below is the code for my first remote view page: <?php include 'header.php'; ?> <script src="/assets/js/ ...

Finding mongoose in an array of objects nested within another object

Here is the MongoDB JSON document I am working with: { categoryId: '1', categoryName: 'Outdoors Equipments', items: [ { itemId: '1', itemName: 'Camping T ...

A guide on retrieving information from a database with PHP and transferring it to Javascript

As I work on creating a website using HTML, CSS, MySQL, and JavaScript, my goal is to allow users to log in and engage in a quiz with 40 questions. Below is the JavaScript code for a countdown timer that includes the "questions" variable. After 40 seconds ...

Utilize AngularJS to inject a service into a module without assigning it to a variable, enabling easier minification

Currently, I am attempting to decrease the size of my AngularJS JavaScript code (using SquishIt). Within my module, there is a service injected as a function argument, as shown below. var myapp = angular.module('myapp', ['ngSanitize'] ...

Do not apply tailwindcss styles to Material-UI

I've been struggling to apply styling from tailwindcss to my MUI button. My setup includes babel and webpack, with the npm run dev script as "webpack --mode development --watch". tailwind.css module.exports = { content: ["./src/**/*.{js, jsx, t ...

Styling a textbox within a gridview using JavaScript

Looking for a way to format a textbox within a gridview using JavaScript? Take a look at how the gridview columns are set up: <Columns> <asp:TemplateField> <ItemTemplate><asp:ImageButton runat="server" id="imgbtnEnterAmt" ...