Skip to content Skip to sidebar Skip to footer

Javascript Function Gets Ignored In Loop

I am building the frontend of a django app with javascript. The script contains this function: function startConverting() { var r=document.getElementById('re

Solution 1:

spr.onresult is asynchronous (this function will only be executed on result, as the name says), so startConverting() is asynchronous. So, getElementById("result").textContent happens way before it has any text content, so it's empty. You absolutely need to await startConverting(), which needs to return a Promise.

function startConverting() {
    return new Promise((resolve, reject) => {
        spr.onresult = function (event) {
            // ... do your stuff ...
            resolve(ftr + interimTranscripts); // Resolve with the text value you need
        };
        spr.onerror = reject;
    });
};


async function askLoop() { // <-- Add async so you can await inside

    var voclisten = document.getElementById("voclisten").textContent;
    var voclistde = document.getElementById("voclistde").textContent;

    for (var i = 0; i < voclistde.length; i++) {

        speakown("was heißt" + voclistde[i]);

        const uservoc = await startConverting(); // <-- Here. This contains the text value returned by resolve()

        var paragraph = document.getElementById("pa");

        if (voclisten[i].includes(uservoc)) {
            var text = document.createTextNode("Correct");
        } else {
            var text = document.createTextNode("Wrong");
        }
        paragraph.appendChild(text);
    }
}

Post a Comment for "Javascript Function Gets Ignored In Loop"