Update cursor immediately before and after a long loop

JS newbie here.

This is an extreme simplification of the real code but the general behavior is the same: after clicking the button I want to change the cursor to “wait”, execute a blocking loop for 3 seconds, and then restore the cursor to “default”.

Is it possible to do this without going through async/await that I have no idea how to use?

let button;
let background_red_color = true;

function long_blocking_loop() {
    // stops 3 seconds here
    let start = new Date().getTime();
    let end = start;
    while(end < start + 3000) {
        end = new Date().getTime();
    }
    background_red_color = !background_red_color;
}


function setup() {
    createCanvas(400,400);

    button = createButton("Click me!");
    button.position(10,10);
    button.mousePressed(() => {
        console.log("Button clicked...");
        button.style("cursor", "wait");  // <= set wait cursor here
        long_blocking_loop();
        button.style("cursor", "default");  //  <= reset cursor here
        console.log("...action completed")
    });

}

function draw() {
    background(background_red_color ? "red":"blue");
}

You don’t want to put blocking code inside an event handler because it will make the app unresponsive. This code works by setting a delayed callback to restart the draw loop

let button;
let background_red_color = true;


function restart() {
  button.style("cursor", "default");  //  <= reset cursor here
  loop();
  console.log("...action completed");
}

function setup() {
  createCanvas(400, 400);

  button = createButton("Click me!");
  button.position(10, 10);
  button.mousePressed(() => {
    console.log("Button clicked...");
    button.style("cursor", "wait");  // <= set wait cursor here
    noLoop();
    setTimeout(this.restart, 3000);
  }
  );
}

function draw() {
  background(background_red_color ? "red":"blue");
}
3 Likes

@quark, thank you, now I understand the logic behind.