javascript - setTimeout not working,am I missing something here? - Stack Overflow

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

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');
    } 
    });

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');
    } 
    });
Share Improve this question edited Oct 12, 2009 at 16:14 Christoph 170k36 gold badges186 silver badges241 bronze badges asked Oct 12, 2009 at 15:53 manraj82manraj82 6,33525 gold badges58 silver badges85 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8

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); 

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');
}

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)

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');
    } 
    });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744236822a4564509.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信