views:

263

answers:

4

I know its pretty basic but I just can't get it to work. it keeps throwing "Object Expected" error...

 $(document).ready(function(){   
    setTimeout('showMessage()', 1000); 

    function showMessage() { 
        alert('abc');
    } 
    });
+6  A: 

The setTimeout method is best used with a function, not a string. Therefore, the best way to do this would be like this:

$(document).ready(function() {
    setTimeout(showMessage, 1000);
});

function showMessage() { 
    alert('abc');
}
SLaks
+1 because you show a working example
Evildonald
+1 for "best used", correctly implying it can be used with a string (but, of course, shouldn't be).
Dan Hook
A: 

You have wrapped your function in quotes, so it treats it like a string, not as the object it's expecting, so, like SLaks said:

 $(document).ready(function(){   
    setTimeout(showMessage, 1000); 

    function showMessage() { 
        alert('abc');
    } 
    });
Anthony
If providing a downvote, please provide a reason why. I don't see a reason here.
Ascalonian
I didn't downvote, but the reason someone did is most likely that string arguments to `setTimeout()` are perfectly fine: the problem lies with visibility of variables
Christoph
+8  A: 

You've got a scoping problem: showMessage() is only visible withing the anonymous function, but when the parameter to setTimeout() gets evaluated, the runtime already left the scope.

Use the function directly as argument to setTimeout() and get rid of the evil[TM] string evaluation:

setTimeout(showMessage, 1000);
Christoph
+1  A: 

The problem is that the showMessage function is declared within the ready event and setTimeout("showMessage()", 1000) will look for it in the global scope. You can move its declaration to a global scope, e.g. out of ready event, or use the SLaks answer: setTimeout(showMessage, 1000)

Kamarey