Generate a series of p5.js instances in a sequential manner using a for loop, ensuring that each new instance is created only

The main issue at hand is related to the execution of multiple sketches in a p5.js instance. Each sketch, representing an in-browser video game, should ideally finish running before the next one begins. However, due to the behavior of the for-loop in defining and running sketches, all sketches end up running simultaneously.

To address this problem and ensure that each sketch completes before the next one starts, it might be necessary to pass specific variables to each sketch that control the execution flow using functions like noLoop() and Loop(). It's a potential solution to coordinate the timing of sketch removal and initiation effectively.

Below is a stripped-down example in HTML showcasing the challenge:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7e3b4e3f203c">[email protected]</a>/lib/p5.js"></script>
    </head>
    <body></body>
    <script>

        /* Function to define sketch with parameter 'a' */
        function defineSketch(a) {
            let sketch = function(p) {
                let x = 100;
                let y = 100;

                p.setup = function() {
                    p.createCanvas(700, 410);
                };

                p.draw = function() {
                    p.background(0);
                    p.fill(255);
                    p.rect(x, y, a*50, a*50);
                };

                /* Remove sketch on mouse press */
                p.mousePressed = function() {
                    p.remove();
                };
            };
        }

        /* Initialize sketch variable */
        let trialSketch;

        /* Array of parameters */
        let param_seq = [0, 1, 2];

        /* For loop to sequentially run sketches with different parameters */
        for(let i = 0; i < param_seq.length; i++ ) {
            trialSketch = defineSketch(param_seq[i]);
            new p5(trialSketch);
        }

    </script>
</html>

Answer №1

According to Pr0tonX on the Processing forum, the solution involves setting a boolean to track if a sketch is running and adding a listener for it:

<!DOCTYPE html>
<html>
    <head>
        <script src="p5.min.js"></script>
    </head>
    <body></body>
    <script>

        // listened variable
        // we set a listner which wiil be fired each time the value of bool is changed.
        let sketchIsRunning = {
            $: false,
            listener: function(val) {},
            set bool(val) {
                this.$ = val;
                this.listener(val);
            },
            get bool() {
                return this.value;
            },
            registerListener: function(listener) {
                this.listener = listener;
            }
        };

        /* Function to define sketch with parameter 'a' */
        function defineSketch(a) {
            return function(p) {
                let x = 100;
                let y = 100;

                p.setup = function() {
                    p.createCanvas(700, 410);
                    console.log('cool')
                };

                p.draw = function() {
                    p.background(0);
                    p.fill(255);
                    p.rect(x, y, a*50, a*50);
                };

                /* Remove sketch on mouse press */
                p.mousePressed = function() {
                    p.remove();
                    sketchIsRunning.bool = !sketchIsRunning.bool
                    console.log('sketch is running ?', sketchIsRunning.bool)
                };
            };
        }

        /* Initialize sketch variable */
        let trialSketch;

        /* Array of parameters */
        let param_seq = [0, 1, 2];

        // we nest a call to the function itself to loop through the param.seq array
        const instanceP5sketches = (i  = 0) => {
            sketchIsRunning.$ = !sketchIsRunning.$;
            trialSketch = defineSketch(param_seq[i]);
            new p5(trialSketch);

            sketchIsRunning.registerListener(function(val) {
                if (param_seq.length - 1 >= i){
                    instanceP5sketches(i+1);
                } else {
                    console.log('No more sketches.')
                }
            });
        }

        instanceP5sketches();

    </script>
</html>

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

Getting information for a Pie Chart in React JS using State: A Step-by-Step Guide

Having just started using React, I've encountered some difficulties in dynamically passing data from my state to Chart.js. Ideally, I want the Pie chart to update automatically whenever a user updates the Textbox and requests the Output. I have stored ...

Interactive jQuery element featuring an image gallery displayed within a translucent black overlay on a webpage

My goal is to add a jQuery popup with an image that appears automatically when a website loads. I envision the popup creating a black transparent overlay, similar to this example. While setting up the basic popup was straightforward, integrating the image ...

How can I create a redirect link in HTML that opens in a new window

I have a HTML page where I need to redirect to the next page. <a href="www.facebook.com" target="_blank">www.facebbok.com</a> Currently, it is redirecting to localhost:9000/dashboard/www.facebook.com But I only want to redirect to www.facebo ...

Error: The attribute 'value' is not recognized on the 'EventTarget' type. Please review the TypeScirpt code

Is there a way to correctly implement the onChange function on a slider in TypeScript and ViteJS without encountering errors with the Value parameter? I'm currently struggling with this issue and would appreciate any guidance or suggestions. Here is ...

Storing a JavaScript variable into a JSON file to preserve data

Is it possible to save data from variables to a JSON file? var json_object = {"test":"Hello"} $.ajax({ url: "save.php", data: json_object, dataType: 'json', type: 'POST', success: ...

Using jQuery to Automatically Add Image Title Attribute from Alt Text

jQuery('img').each(function() { if(jQuery(this).attr('title') === '') { jQuery(this).attr('title', jQuery(this).attr('alt')); } }) Is there a way to tweak the code snippet above so that it ...

Stop a hyperlink from refreshing the webpage

Currently, I am in the process of developing a responsive menu. You can view a demo of my progress on Codepen. In order to prevent the page from reloading when I click a link within the menu, I have implemented the following JavaScript code: $('nav. ...

Why is the raycaster unable to detect the object that has been loaded in three.js?

I am new to THREE.js. I would like to implement a feature where clicking the mouse selects a loaded .obj object in the scene, highlights it by making it half transparent, and then allows the object to follow the mouse as it moves. Subsequently, another cli ...

Clearly state the action of the form

I have utilized html, JavaScript, CSS, and JQuery to create a website template. Within this template, there is a file called contact.js that contains the ajax code for handling forms: $(function() { submitSuccess: function($form, event) { ...

Is there a way to run JavaScript from an external HTML/SVG file using only pure JavaScript?

I am facing an issue with executing JavaScript in an SVG file when including it in an HTML document using AJAX. The behavior differs depending on whether I use jQuery to include the SVG or pure JavaScript. If I open the SVG file alone, its JavaScript ru ...

Switching between numerical and alphabetical input using JQuery

How can I switch between allowing character and numeric input in a textbox? I currently have a JQuery function that restricts input to numbers only $('.numeric').on('input', function (event) { this.value = this.value.replace(/[^0 ...

The request is not functioning as expected for some reason

My current challenge involves retrieving photos from Instagram using a GET request. I attempted to use jQuery.get(), which has been successful for other types of GET requests but not for Instagram. Despite trying to switch to jQuery.getJSON(), the issue pe ...

ReactAppI am facing an issue where the browser fails to refresh the page upon saving changes in my JavaScript file using the VS code editor

Can anyone remind me of the tool we can install to refresh the browser page automatically whenever we save changes in our editor? ...

Retrieving an array of JSON data from an HTTP response

Recently starting my journey with AngularJS for a project, I've encountered a challenge in extracting a json array from an http response to utilize in a list. Here's a glimpse of the response structure: { "DFH0XCMNOperationResponse": { "c ...

Utilizing Filepond to extract base64 data in a React JS environment

Struggling to extract a base64 from an image upload and send it along with other values to the server. Due to API limitations allowing only 2 files at a time, I'm unable to process uploads individually. Having difficulty in mapping the 'data&apo ...

Event handler class fails to determine the checkbox status

I am attempting to bind the change event of certain checkboxes by class and then check whether the checkbox is being checked or unchecked for further processing. However, I am facing an issue where the "nope" alert always pops up, regardless of the checkbo ...

Searching in Datatables by the first letter of each column

I'm currently developing a web app with a datatable functionality. I have implemented both a global search bar and individual search bars in each column, similar to this example: https://datatables.net/examples/api/multi_filter.html. Now, my goal is t ...

Place items into the text box on an HTML webpage

Is there a way to add more than one element into a textbox using jQuery, and then insert them into a database? Currently, the script only adds one element at a time when I attempt to add another one that was previously removed. Any suggestions on how to ac ...

Ways to conceal various components while showcasing just a single element from every individual container

I am looking to only display specific span elements within their parent container (coin) while hiding the rest. The desired output should show only "1" and "first" while the other spans are hidden. <div class="types"> <div class=" ...

What are some effective strategies for sharing information in JavaScript?

I have an ASP.NET website and I need to pass information to JavaScript for some tasks. Currently, I am using the following method: <script type="text/javascript"> var userHasMicrositePhoto = '<%=hasMicrositePhoto%>'; </script& ...