Click here to Skip to main content
15,886,689 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all Im new to P5.js and want to know if I can slow down the rate at which each line is drawn. Im not good at clent side stuff but well versed in server side. Every delay, setTimeout() or other IIFE delay I place in the for loop just doesn't do what I want it to. Is there a command in P5 that can do this or do I need to refactor my code?


<pre>function setup() {
    createCanvas(1600,1600)
}

function getRandomInt(min, max) {
    min = Math.ceil(min)
    max = Math.floor(max)
    return Math.floor(Math.random() * (max - min) + min)
  }

async function draw() {
    let dataValue1 = null, dataValue2 = null, timeMultiplier = 20

    for (let time = 50; time < 1200; time += timeMultiplier) {
        if (!dataValue1) { dataValue1 = 200 }
        dataValue2 = getRandomInt(100,500)
        
        // add a delay here.... but doesn't work as expected
         
        line( time - timeMultiplier, dataValue1, time, dataValue2 )
        dataValue1 = dataValue2
    }
    noLoop()
}


What I have tried:

setTimeout(()=>{}, 1000)


plus other self resolving promise
Posted
Updated 28-Nov-21 12:48pm
v2
Comments
0x01AA 28-Nov-21 11:41am    
Try await sleep(200);
cyber dean 28-Nov-21 16:19pm    
thanks, didn't work. I think something along the lines of this may work - https://stackoverflow.com/questions/56094678/how-to-delay-the-drawing-of-elements-in-p5

1 solution

THIS WORKS!
Great site sending big 2 fingers to stack exchange!

let value1 = 500

function setup() {
    createCanvas(1600,1600)
    noLoop()
}

const sleep = (millis) => { 
    return new Promise(resolve => setTimeout(resolve, millis)) 
}

function getRandomInt(min, max) {
    min = Math.ceil(min)
    max = Math.floor(max)
    return Math.floor(Math.random() * (max - min) + min)
  }

async function draw() {
    let time = frameCount * 20
    let value2 = getRandomInt(100,500)
    line( time - 20, value1, time, value2 )
    value1 = value2
    await sleep(100)
    if (time < 1200) { redraw() } else { myProgram() }
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900