Halting Execution After Placing an Object in Three.js Scene with Javascript

It seems like a simple task, but I've been struggling with it for days.

How can I add objects to a scene with a pause between each addition?

Inside a loop{

I call the make_obj function()

then I call the wait function()

}

The issue is that the program doesn't display each added object with a pause; instead, it waits until the loop ends and then shows all the objects together on the screen after all pauses have been completed.

I've tried to explain this before

Three.js scene not reacting while program is running

but it seems too complicated, so I'm breaking it down here.

Thank you in advance.

Edit_1: Yes, I can. Please consider the scene and three as objects inserted by another class. These are standard instantiations.

test = function (scene, three){

    this.scene = scene;
    this.caller_inst = three;

    var that= this;
    var depth_mod=0;

    this.start_loop=function(){

        var i;

        for(i = 0; i < 10; i++){
            this.make_objects();
            this.wait(1000);
        }
    };

    this.wait = function(ms){

        setTimeout(function(){ console.log("Wait!"); }, ms);
        return;

        console.log("wait start");
        var start = new Date().getTime();
        var end = start;

        while(end < start + ms){
            end = new Date().getTime();
        }
        console.log("wait ended");
    };

    this.make_objects = function(count_rows, count_columns){

        var color = '#'+Math.floor(Math.random()*16777215).toString(16);
        var sphere_geometry = new THREE.SphereGeometry(1);
        var material1 = new THREE.MeshPhongMaterial({ color: color, specular: 0x555555 });
        var sphere_mesh = new THREE.Mesh(sphere_geometry, material1);

        this.scene.add(sphere_mesh);

        sphere_mesh.position.copy(that.caller_inst.camera.position);
        sphere_mesh.position.x = sphere_mesh.position.x+5+depth_mod;
        sphere_mesh.position.z = sphere_mesh.position.z-15 + depth_mod;

        that.caller_inst.renderer.render(that.caller_inst.scene, that.caller_inst.camera);
        depth_mod = depth_mod-1;
    };

};

I made a slight modification but got the same result.

this.start_loop=function(){

var i;

for(i = 0; i < 10; i++){
    setTimeout(function(){ that.make_objects(); }, 1500);
}

};

Why doesn't manual waiting work like this:

var i;

for(i = 0; i < 10; i++){
    this.object[i].visible = true;
    this.wait(1000);
}

?

Answer №1

Implementing setTimeout for delayed execution.

Create a function that adds an object, and then execute it using setTimeout. For multiple additions, simply include another setTimeout call at the end of your object-adding function.

function greet() {
  alert('Hello');
}

setTimeout(greet, 1000);

For more examples, visit this page: https://javascript.info/settimeout-setinterval

Answer №2

Exploring various techniques for implementing a loop with a pause reveals the modern ES6 approach using async functions.

const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

async function executeTasksWithDelay() {
  for (let i = 0; i < 10; ++i) {
    console.log(i);    // add object here
    await wait(1000);  // wait 1 second
  }
}

executeTasksWithDelay();

illustrative example:

<canvas id="c"></canvas>
<script type="module">
import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r113/build/three.module.js';

const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

async function main() {
  const canvas = document.querySelector('#c');
  const renderer = new THREE.WebGLRenderer({canvas});

  const fov = 40;
  const aspect = 2;  // the canvas default
  const near = 0.1;
  const far = 50;
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  camera.position.z = 16;

  const scene = new THREE.Scene();

  {
    const color = 0xFFFFFF;
    const intensity = 1;
    const light = new THREE.DirectionalLight(color, intensity);
    light.position.set(-1, 2, 4);
    scene.add(light);
  }

  const boxWidth = 1;
  const boxHeight = 1;
  const boxDepth = 1;
  const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);

  function makeInstance(geometry, color, x) {
    const material = new THREE.MeshPhongMaterial({color});

    const cube = new THREE.Mesh(geometry, material);
    scene.add(cube);

    cube.position.x = x;

    return cube;
  }

  const cubes = [];

  function animate(time) {
    time *= 0.001;  // convert time to seconds

    cubes.forEach((cube, ndx) => {
      const speed = 1 + ndx * .1;
      const rot = time * speed;
      cube.rotation.x = rot;
      cube.rotation.y = rot;
    });

    renderer.render(scene, camera);

    requestAnimationFrame(animate);
  }
  requestAnimationFrame(animate);

  const numCubes = 11;
  for (let i = 0; i < numCubes; ++i) {
    const u = i / (numCubes - 1);
    const x = (u * 2 - 1) * 10;
    cubes.push(makeInstance(geometry, `hsl(${u * 360},100%,70%)`, x));
    await wait(1000);
  }   
}

main();
</script>

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

Identify data points on the line chart that fall outside the specified range with ng2-charts

I'm struggling to figure out how to highlight specific points on a line chart that fall outside a certain range. For instance, if the blood sugar level is below 120, I want to display that point as an orange dot. If it's above 180, I want to show ...

The NextJs image entered into an endless loop, throwing an error message that said: "The 'url' parameter is correct, but the response from the

I have been using next/image component with next js version ^12.2.3-canary.17 for my current project. The issue I am encountering is that some images are missing from the source directory, resulting in infinite error logs like the one shown below: https:/ ...

Double dragenter events triggered before dragleave in HTML5 drag and drop functionality

Currently, I'm researching HTML5 Drag and Drop functionality by using this resource. However, I've encountered an issue with the dragenter event that seems to fire twice for child elements before the dragleave event. Because of this, the dashed b ...

Exploring the process of passing an array as a function argument from PHP to JavaScript

I am looking for assistance in passing an array as a function argument from PHP to JS. The values I need are retrieved from a database. while ($rows = pg_fetch_array($qry)) { ?> <option value="<?php echo $rows[&ap ...

How to Implement Flexbox Display Across Various Browsers Using jQuery?

Running into an issue here. I'm trying to switch from display: none to display: flex, display: flex-box, and display: -ms-flexbox but for some reason it's causing errors in my code.. Here's what I've been working on: $(elem).css({&apos ...

Trouble with ScrollTo animation on div with adjustable offset top feature - seeking assistance

Having trouble navigating to the correct slide when clicking the right button on the navigation menu. Clicking the menu button displays a list of links. Clicking on a link for the first time will take you to the correct slide, but if you try clicking a dif ...

Unable to navigate through select2 dropdown if fixed div is present

I am facing an issue with select2 in my fixed div popup that acts like a modal. The problem is that when the select2 dropdown is open, I am unable to scroll the div until I close the dropdown. This becomes problematic on smartphones because the keyboard e ...

Utilize a React function to incorporate an external link

Looking to create a link to Twitter using the href attribute but encountering errors with the atag. Is there an alternative method I could use? In essence, I want to have a picture on my homepage that, when clicked, redirects the user to Twitter. I' ...

Upon completion of an Ajax call, ReactJS will execute a callback function

I'm relatively new to React and encountering an issue. I am fetching data from an API that requires a callback function as a parameter (&callback=cb). I've chosen to use the fetchJsonp library for making cross-domain fetch requests. Despite pass ...

What is the best way to transfer the text from an input field into a paragraph when a button is

For a school project, I am developing a website focused on time management. My goal is to create an input text box that, when the "add task" button is clicked, transfers the text inside it to a paragraph or p2 element and then moves the input field down. ...

What leads to the occurrence of the "maximum call stack size exceeded" error?

I am currently developing a Vue 3 and Bootstrap 5 application. To integrate a date-picker functionality, I opted for the Vue 3 Datepicker plugin available at Vue 3 Datepicker. Within the file components\Ui\Datepicker.vue, I have included the fol ...

Navigating through an array in Pug

I'm currently extracting data from an external API in JSON format and sending it to my view. The main issue I'm facing is that one of the properties within the Object consists of an Array of Objects. Using the Pug Documentation for iteration, I&a ...

A step-by-step guide on generating a dynamic JSON file with JavaScript

I am in need of generating a JSON structure that follows this specific format: {"content": { "properties": { "area_id": "20", "origin": "3", "axis": "1", "x_start": "00", "x_end": "99", "y_start": "00", ...

Ways to make a jsonp request without including the 'callback' in the URL

I've been working on retrieving information from an Icecast Radio station using their API, which offers the status-json.xsl endpoint to access this data. Despite the format being in xsl, I suspect it returns a JSON file. However, I've encountere ...

Check to see if the ContentEditable div is currently focused

I'm struggling to determine if a contenteditable div has focus with my current code. Here is what I have so far: if ($("#journal-content:focus")) { alert("Has Focus"); } else { alert("Doesn't Have Focus"); } The issue I'm encounter ...

Having trouble installing gulp locally due to an error with ` ode_modulesansi-regex`

While attempting to set up Gulp on my Windows 10 system, I encountered an error during the local installation process. $ node -v v9.10.1 $ npm -v 5.6.0 I successfully installed Gulp globally: $ npm install --global gulp-cli $ gulp -v CLI version 2.0.1 ...

Utilizing JavaScript: Storing the output of functions in variables

Currently in the process of learning JavaScript and aiming to grasp this concept. Analyzed the following code snippet: function multiNum(x, y){ return x * y; } var num = multiNum(3, 4); document.write(num); Decided to try it out on my own, here's ...

Tips for recognizing a specific object ID within an array in order to modify the status of an element within that object

My goal is to accurately identify a specific panel within an expanded array and link that panel's ID to a button, while also ensuring the button is disabled when no panels are expanded or more than one panel is expanded. However, I am encountering iss ...

Tips for building a task list using JavaScript only

Is it possible to create a to-do list using only JavaScript in an HTML file with a single div tag? Here is my HTML file for reference: example Here is the structure of my HTML file... <!DOCTYPE html> <html lang="en"> <head> ...

Verifying the "select" dropdown option prior to final submission

My website features multiple select dropdowns that require validation before submission. For instance, there may be a situation where seven select dropdowns are present as described below. My desired validation criteria is: If there are 5 or more "sel ...