Skip to main content

Cancelling waitFor

As we learned earlier, waitFor will repeatedly search our screen for a given template image.

This great flexibility does not come for free, so we might not want to wait for the timeout to fire before we can cancel the ongoing search. nut.js follows the same approach to cancellation as the browser fetch API, using an AbortController.

Before we can actually look at a sample, we will have to install an additional package to our project:

npm i node-abort-controller

Now, let's take a look at an (rather artificial) example:

const { screen, Region } = require("@nut-tree/nut-js");
const AbortController = require("node-abort-controller");
(async () => {
const controller = new AbortController();
screen.waitFor("test.png", 5000, {abort: controller.signal});
setTimeout(() => controller.abort(), 2000);

We instantiate our AbortController in line 5 and pass its signal as an OptionalSearchParameter to waitFor.

waitFor has a timeout of 5000 milliseconds configured, but after 2000 milliseconds, we call abort() on our AbortController, which will cancel the ongoing search:

Action aborted by signal