简体   繁体   中英

How do I make a pause in-between commands in p5js?

Title. I want to add to a variable every "x" seconds. Basically, this is what I want:

var count;

function draw() {
  //...

  count.count();
}

function count() {
  this.count = function() {
    pause(x);
    count++;
  }
}

I've looked in the reference but I can't find anything that would help me achieve this.

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

set_time_out

// simple example
var seconds = 3;

setTimeout(function() {
  // your code to be executed after 3 second
  // Since it is in milliseconds units, multiply it by 1000.
}, seconds*1000);

Promise
async_function
async/await

// using Promise & async/await
let value = 0;
let seconds = 3;

const pause = (t) => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(value++);
        }, t*1000);
    });
}

const count = async () => {
    await pause(seconds);
}

const main = async () => {
    console.log(value);
    await count();
    console.log(value);
}

main();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM