Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
70 views
in Technique[技术] by (71.8m points)

javascript - Set timeout() method is not working when defining an index after the function name in HTML?

I have a problem with executing a set timeout on a function in HTML I will show you 2 examples one that works the other simply ignore the set timeout method

Working example :
A: onclick="setTimeout(hideBtn, 1000)" in this example the hidenBtn does not have and index() attached to it and the 1sec delay simply works.

Problematic example : B: onclick="setTimeout(hideBtn(0), 1000)" in this example once I define and array index after the function the set time get ignored and the function executes right on click.

do you see any problem with the syntax ?

I will link the whole function from the JS file because I tried to set the set Time out from there but and error occur saying the whole function is not defined ? since I need the index to be defined I cannot go with working example. thanks for help.

let g = document.querySelectorAll(".populating-btns");

function hideBtn(index) {
    for (let i = 0; i < g.length; i++) {
        g[index].style.display = "none";
    }
};
<div id="removeA" class="populating-btns">
        <div class="add-btn-extend" onclick="setTimeout(hideBtn(0), 1000)">
            <span>Hide1</span>
        </div>
    </div>
    
    
    <div id="removeB" class="populating-btns">
        <div class="add-btn-extend" onclick="setTimeout(hideBtn(1), 1000)">
            <span>Hide2</span>
        </div>
    </div>
question from:https://stackoverflow.com/questions/65928461/set-timeout-method-is-not-working-when-defining-an-index-after-the-function-na

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

setTimeout needs a function object as its first parameter.

What happens now is this:

  • The function call hideBtn(0) is executed.
  • When it ends, it returns undefined.
  • That undefined then gets passed into the setTimeout(....) function.

The fix is to create a small new anonymous function using lambda or arrow notation, and pass that anonymous function into setTimeout:

<div class="add-btn-extend" onclick="setTimeout(() => hideBtn(0), 1000); fadeClick(0);">
    <span>Previous history</span>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...