Pie
Pie

Reputation: 937

Javascript SetTimeout Function Not Pausing After Execution

I am checking for a change in a CSS class. I want the check to happen every 1000 milliseconds. Currently in the Google Chrome console, I can see it checking without any delay, causing the webpage to crash. What is the issue with the below setTimeout function? Perhaps there is another way of checking for a change in a CSS class also?

var itemInfo = null;

itemInfo = document.getElementById('option-item-info');
while (itemInfo.className == "disabled") {
    console.log("Test 1");
    getOptionItemInfo();
}

function getOptionItemInfo() {
    setTimeout(function() {
        console.log("Checking...");
        itemInfo = document.getElementById('option-item-info');
    }, 1000);
}

Upvotes: 0

Views: 36

Answers (1)

Nick
Nick

Reputation: 16576

Your while loop isn't going to wait for the setTimeout async callback, it's just going to trigger tons of setTimeouts until your browser crashes. Instead, just kick off the setTimeout once and then only call it again from within the callback if you haven't met the desired condition.

getOptionItemInfo();

function getOptionItemInfo() {
    setTimeout(function() {
        console.log("Checking...");
        var itemInfo = document.getElementById('option-item-info');
        if (itemInfo.className == "disabled") {
            getOptionItemInfo(); 
        } else {
            console.log("done!");
        }
    }, 1000);
}

Upvotes: 5

Related Questions