Veselin Aleksandrov
Veselin Aleksandrov

Reputation: 3

JavaScript function not working unless it has setTimeout

function sayHello(name)
    {
        var prompt = "Hello, " + name + "!";
        function asd()
        {
            alert(prompt);
        }
    }

This code is not working. I have an HTML file with a button, that has an onClick='sayHello("MyName")'. It doesn't work, unless I add a setTimeout(asd, 0); after the inner function. Any idea why (or what I'm doing wrong)? I'm just starting JS and this is very strange to me.

Upvotes: 0

Views: 99

Answers (1)

Paul S.
Paul S.

Reputation: 66364

Remember to invoke your function.

function sayHello(name) {
    var prompt = "Hello, " + name + "!";
    function asd() {
        alert(prompt);
    }
    asd(); // invoke
}

Upvotes: 3

Related Questions