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

Issues encountered while utilizing Bliss as the template engine in NodeJS/Express

Seeking assistance in transitioning from Jade to Bliss as the template engine for a basic Express web application on NodeJS. Here is the code snippet from app.js: var express = require('express'), routes = require('./routes'), ...

Exploring the power of AngularJS with ng-click functionality and utilizing services

As a beginner in AngularJS, I am facing a knowledge gap when it comes to integrating a barcode scan feature into my application. What I want to achieve is quite simple - a button in the view that, when clicked, triggers a barcode scan. Once the scan is com ...

Troubleshooting CSS override issues when swapping components in ReactJS

Access.js import React from 'react' export default class Access extends React.Component { componentWillMount(){ import ('./styles/access_page.css'); } .... <Link to="/new-account">Sign Up</Link> } Cr ...

Utilize jQuery to load AngularJS libraries into your web application

Trying to incorporate AngularJS into a jQuery-built webpage has been my latest challenge. While the rest of the site was developed using jQuery, I wanted to tap into the potential of AngularJS for a specific page. That's when I decided to do this: jQ ...

Assign the value/text of a div element by using JavaScript/jQuery within a PHP loop

I'm struggling to figure out how to set the value/text of a div using javascript/jquery inside a loop. Can anyone offer some guidance on this issue? Goals: Extract data from a database. Use javascript/jquery to assign the extracted data to an eleme ...

Tips for accessing child elements within an Angular component

I'm struggling to get a reference of child elements within a component. I have experimented with ElementRef, TemplateRef, QueryList, ViewChild, ViewChildren, ContentChild, and ContentChildren without success. <app-modal> <section #referenc ...

Can React components be saved in an array?

I am currently working on enhancing the code snippet provided below. This code is intended to iterate through elements of an array using keys to locate images within a lengthy SVG file directly embedded in the document under the identifier "SomelongUglySVG ...

Tips for invoking or triggering the Ajax change function when there is only a single option available

<select class="custom-select custom-select-sm mb-3" required="true" id="sel_block"> <option value="0">Select Block From Here</option> <?php // Fetch Blocks $sql_block = "SELECT * FROM blocks WHER ...

Revolutionizing Form Select Field: Introducing Rails' Dynamic Input Rendering

I'm a beginner in coding, so please bear with me if my question sounds amateurish. Currently, I am developing an e-commerce website where customers can order posters from images uploaded to the site. They should be able to choose the size of the poste ...

Encountering a rollbackFailedOptional error during the NPM Install process

When attempting to use various command prompts like Windows Powershell, command prompt as an admin, and bash CMD, I encountered the same error message after trying to run npm install: npm install npm@latest -g The specific error message was: [...] / ro ...

React: Show input value on button click

I have been working on a React form that displays the entered input value in a controlled input element only after the user hits the submit button, rather than updating it constantly as the user types. Here is my current solution using conditional renderin ...

Discover the method for extracting the value from an array that has been transferred from a php script

So here's the situation - I have a text file containing data. The first step is to convert the content of the text file into an array. $lines = file($filename); Next, the data is sent back to the client (the $filename is determined through ajax). ...

Why is Jasmine throwing an error when I try to use getElementsByTagName(...)?

HTML: <ul id="listONE"> <li class="{{isSel}}" ng-repeat="person in people" ng-click="selPersonToChange(this)">{{person.name +" - "+ person.city}}</li> </ul> A snippet from my script.js using AngularJS (1.3.1): mymod.control ...

Updating JSON when the color changes in Go.js can be achieved by implementing event listeners and

I've been using Go.js for creating Flow charts and saving the json data into a SQL database. However, I'm facing difficulties in updating the json data. Here is the code snippet: myDiagram.addDiagramListener("ChangedSelection", function (e1) { ...

Image Switching Hover Bug

HTML: <div id="logo"></div> <div id="coming-soon"></div> JavaScript: $(document).ready(function(){ $("#logo").hover( function(){ $("#logo").fadeTo(300, 0); $("#coming-soon").fadeTo(300, 1.0 ...

AngularJS - Ensuring the <script> tag is included only after all directives have been rendered

Forgive me if this question has been asked before. I've spent quite some time looking for a solution to no avail. I'm in the process of converting an existing application, which relies heavily on jQuery, to utilize AngularJS. However, I've ...

Error encountered during navigation: navigator has not been defined

I encountered an issue where the page gets redirected upon form submission without triggering the catch block. However, in the backend, I am facing an error stating that the API body is not being executed. Below is the code snippet of the page: "use cl ...

The ball refuses to fall into the designated boxes

I designed a basic webpage featuring 3 boxes that, when clicked on, trigger the dropping of a ball into them. Below is the code I used: <!DOCTYPE html> <html> <head> <script type="text/javascript"> function popup (n) { ...

Transforming jQuery into vanilla JavaScript in order to create a customized dropdown select functionality

I am struggling with converting jQuery code to pure JavaScript for a custom select element. https://codepen.io/PeterGeller/pen/wksIF After referencing the CodePen example, I attempted to implement it with 3 select elements. const select = document.get ...

A comprehensive guide on utilizing the loading.tsx file in Next JS

In the OnboardingForm.tsx component, I have a straightforward function to handle form data. async function handleFormData(formData: FormData) { const result = await createUserFromForm( formData, clerkUserId as string, emailAddress a ...