Category: JS Objects
Resource links

This solution is summarized from an archived support forum post. This information may have changed. If you notice an error, please let us know in Discord.

How Do I Get a Javascript Loop to Work with an API?


I am trying to run a while loop synchronously in my JavaScript code to control a process by checking its status and querying an API endpoint every few seconds. However, I am not experienced in JavaScript and the loop is not logging anything in the console. After seeking help, I learned that my approach was not correct and I needed to make my function asynchronous and separate the query result before using it in an if statement. Now, my code works correctly, although I have not been able to add a delay to the loop.


The problem was that the while loop in the function loopScanStatus was not running correctly and was not logging anything to the console. The goal was to control a process by checking its status every few seconds after launching it from a button on the UI.

The solution involved making the loopScanStatus function asynchronous and getting the result of the query separately using await. The new code looks like this:

async function loopScanStatus() {
    while (true) {
        const data = await;
        if (data === "FINISHED") {
} => loopScanStatus());

This fixed the issue, and the loop now waits for the API response before executing again. The function logs the response to the console and ends the loop once the response is "FINISHED".