简体   繁体   中英

Why does setTimeout execute function without delay?

I have wrote following code:

// callback function
function tryMe (param1) { 
    alert (param1 ); 
} 

// callback executer 
function callbackTester (callback) { 
    callback(); 
} 

// test function
    callbackTester (  function() {
        setTimeout(  tryMe(1), 10000);
     })

I see alert at once after script execution.

Expected result - see alert with delay 10 seconds.

Where do I wrong?

How to correct this code?

You could do that:

setTimeout(function() { tryMe(1) }, 10000);

In this case the tryMe(1) function will be invoked after the specified interval. In your example you were immediately invoking the function.

Basically the setTimeout function takes a function pointer as first parameter whereas you passed tryMe(1) as first parameter which is the result of the execution of this function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM