Search code examples
javascriptcallbackdelay

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?


Solution

  • 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.