简体   繁体   中英

Problem with setTimeout and anonymous function in Javascript

Why this doesn't work in Firebug console:

function(s,e) {
setTimeout(function(){grvClosingDocs.Refresh();CBPDocFlow.PerformCallback();},100)
}

While this does:

setTimeout(function(){grvClosingDocs.Refresh();CBPDocFlow.PerformCallback();},100)

It doesn't work because you don't call the other anonymous function wrapping your setTimeout, how is it actually called?

You have to either name it and call it:

function someFunc(s,e) {
    setTimeout(function(){grvClosingDocs.Refresh();CBPDocFlow.PerformCallback();},100)
}
someFunc();

Or wrap it in parens and call it immediately

(function(s,e) {
    setTimeout(function(){grvClosingDocs.Refresh();CBPDocFlow.PerformCallback();},100)
})();

Or name it and call it on document load:

JS :

function someFunc(s,e) {
    setTimeout(function(){grvClosingDocs.Refresh();CBPDocFlow.PerformCallback();},100)
}

HTML

<body onload='someFunc'>
....

Because you're not calling the function in the first example. You need to call the function, which you can do as follows. The parentheses around the function are there to prevent a syntax error: a function expression (which is what your example is) on its own is not a valid statement. The parentheses at the end call the function.

(function(s,e) {
  setTimeout(function(){grvClosingDocs.Refresh();CBPDocFlow.PerformCallback();},100)
})();

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