javascript - What should be the correct signature of the given method -


this function have

frmloadingtimerid = settimeout("updateknl('"+ strtype +"')",500); 

where value of strytype string . in updateknl method switch statement there therefore strtype should followed , ended ''. want send parameter along function not getting proper way so.

i have tried following code

frmloadingtimerid = settimeout("updateknl('"+ strtype +"',abc)",500); 

and

frmloadingtimerid = settimeout("updateknl('"+ strtype +"',+"abc")",500); 

in both way value not passed undefined error throw if try assign value of abc other variable.

none of snippets correct, since settimeout expects function reference first argument, not string. can pass string, check mdn says that:

code in alternate syntax string of code want execute after delay milliseconds (using syntax not recommended same reasons using eval())

as know, eval evil, , has few valid use-cases. in case, there's better way go business, that's why answer is:

frmloadingtimerid = settimeout(function() {     //read updateknl(somevar, 'astring', 123, ['an','array'],{some:'object'});     return updateknl(strtype, abc);//pass 2 variables },500); 

you might want pay notice few conventions there in terms of variable-names in js: variables start lower-case letter, , cammelcased, functions start lowercaseandarecammelcased, too, unless function constructor, in case it's start uppercase char.

anyway, code above should fix problem, advised, though, if of 2 variables change value in 500ms before timeout calls callback function, altered values used. avoid this, use iife create closure:

frmloadingtimerid = settimeout((function(strtype, abc) {// assignes passed arguments these vars //     return function()     {         return updateknl(strtype, abc);//uses arguments of iife     }; }(strtype, abc)),500);//pass current values of these variables here 

read tag wiki, explains how construction works, , why should use (it's similar infamous loop problem).

if, reason, want persist , maintain madness of passing strings settimeout:

settimeout("updateknl('" + strtype + "', 'abc')",500); 

this passes string value of strtype , string constant 'abc' function. if abc variable, should referenced when timeout delay ended:

settimeout("updateknl('" + strtype + "', abc)",500); 

by removing quotes around abc, @ end of timeout, string behaves if passed eval: eval("(updateknl('" + strtype + "', abc))"), indeed evil. abc might have been reassigned time delay ends... must urge refactor code


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -