Why is the method executed immediately when I use

2018-12-31 08:34发布

This question already has an answer here:

I'm trying to write a simple code with a setTimeout and the setTimeout just won't wait the time it's supposes to and the code execute immediately. what am i doing wrong?

 $("#btn1").click(function () {
    if ("something") {
        $("#div1").slideUp();
        setTimeout(testfunction(), 2000);
    }
 }

标签: javascript
4条回答
浪荡孟婆
2楼-- · 2018-12-31 08:59

Remove the parenthesis after the testfunction name:

setTimeout(testfunction, 2000);

The reason is that the first argument to setTimeout should be a function reference, not the return value of the function. In your code, testfunction is called immediately and the return value is sent to setTimeout.

查看更多
情到深处是孤独
3楼-- · 2018-12-31 09:08

Remove the parenthesis

setTimeout(testfunction(), 2000);

If you want to send parameters to the function, you can create an anonymous function which will then call your desired function.

setTimeout(function() {

    testfunction('hello');

}, 2000);

Edit

Someone suggested to send a string as the first parameter of setTimeout. I would suggest not to follow this and never send a string as a setTimeout first parameter, cause the eval function will be used. This is bad practice and should be avoided if possible.

查看更多
高级女魔头
4楼-- · 2018-12-31 09:17

Well you might have got the answer but I am explaining the cause and solution. There are two ways in which you can call a function after required amount of time.

1. setTimeout("FUNC_NAME ()', TIME_IN_MS);
Here FUNC_NAME inside double quotes is the original function you want to call after TIME_IN_MS milliseconds. This is because if you do not put the quotes then while java script is getting interpreted the function would be immediately executed and your purpose would get defeated. To let interpreter skip the statement we need to put quotes here.
2. setTimeout(function () {FUNC_NAME ()}, TIME_IN_MS);
Here anonymous function is created that tells interpreter to execute if after certain time instead of evaluating time.

Thanks shaILU

查看更多
临风纵饮
5楼-- · 2018-12-31 09:19

You're calling the function immediately and scheduling its return value.

Use:

setTimeout(testFunction, 2000);
                       ^

Notice: no parens.

查看更多
登录 后发表回答