Skip to content Skip to sidebar Skip to footer

What Should Be The Correct Signature Of The Given Method

This is the function i have FrmLoadingTimerID = setTimeout('UpdateKnl(''+ strType +'')',500); where value of strytype is a string . In the UpdateKnl method switch statement is the

Solution 1:

None of your snippets are correct, since setTimeout expects a function reference as first argument, not a string. You can pass a string, but just check what MDN says about that:

code in the alternate syntax is a string of code you want to execute after delay milliseconds (using this syntax is not recommended for the same reasons as using eval())

As we all know, eval is evil, and has but few valid use-cases. In this case, there's a better way to go about your business, so that's why the answer is:

FrmLoadingTimerID = setTimeout(function()
{
    //read as UpdateKnl(someVar, 'aString', 123, ['an','array'],{some:'object'});
    return UpdateKnl(strType, abc);//pass 2 variables
},500);

You might want to pay notice to the few conventions there are in terms of variable-names in JS: Variables start with a lower-case letter, and are cammelCased, functions start with a lowerCaseAndAreCammelCased, too, unless the function is a constructor, in which case it's to start with an UpperCase char.

Anyway, the code above should fix your problem, but be advised, though, that if any of the 2 variables change value in the 500ms before the timeout calls its callback function, the altered values will be used. To avoid this, use an iife to create a closure:

FrmLoadingTimerID = setTimeout((function(strType, abc)
{// assignes passed arguments to these vars //returnfunction()
    {
        returnUpdateKnl(strType, abc);//uses arguments of IIFE
    };
}(strType, abc)),500);//pass current values of these variables here

Read the tag wiki, it explains how this construction works, and why you should use it (it's similar to the infamous loop problem).

If, for some reason, you want to persist and maintain the madness of passing strings to setTimeout:

setTimeout("UpdateKnl('" + strType + "', 'abc')",500);

This passes the string value of strType and a string constant 'abc' to the function. If abc is a variable, that should be referenced when the timeout delay is ended:

setTimeout("UpdateKnl('" + strType + "', abc)",500);

By removing the quotes around abc, at the end of the timeout, the string behaves as if it were passed to eval: eval("(UpdateKnl('" + strType + "', abc))"), which is indeed evil. abc might have been reassigned by the time the delay ends... so I must urge you to refactor this code

Post a Comment for "What Should Be The Correct Signature Of The Given Method"