Skip to main content

Oddity with For loops in ServiceNow!

Not for the first time, I have noticed issues with For loops in ServiceNow


for (i=0;i<10;i++){

      ....

}


The loop can at times appear to get stuck and the 'i' counter stops incrementing. Having not yet got to the bottom of it, I can only assume that some other object behind the scenes is already using 'i' , or possibly several client scripts using i exist on the form, though in theory the functions should encapsulated.
The problem certainly seems to go away by replacing the above with something like:

for (i_counter=0;i_counter<10;i_counter++){

      ....

}

Hence, I can't say I could recommend using the 'i' variable anywhere in for loops when coding in ServiceNow!

...Watch this space, I may post more once I get to the bottom of why this happens!...

Comments

  1. maybe including var i=0 instead of just i=0 helps...
    for(var i = 0; i < favorites.length; i++) {

    ReplyDelete
  2. Ran across this one. It was scoping issue - instead of
    for([var] i = 0; i<counter; i++){gs.print(i)}; enclosure helps:
    function() { var x,y,z,i; //<- all local
    for (i=0;i<10;i++){
    gs.print(i);
    }
    so the I is always local to anonymous/function rather than i's in scripts includes. HTH

    ReplyDelete
    Replies
    1. Good call Max, thank you. Enjoy the Knowledge18 event mate

      Delete

Post a Comment

Popular posts from this blog

ServiceNow check for null or nil or empty (or not)

Haven't tested these all recently within global/local scopes, so feel free to have a play! option 1 use an encoded query embedded in the GlideRecord , e.g.  var grProf = new GlideRecord ( 'x_cls_clear_skye_i_profile' ); grProf . addQuery ( 'status=1^ owner=NULL ' ); grProf . query (); even better use the glideRecord  addNotNullQuery or addNullQuery option 2 JSUtil.nil / notNil (this might be the most powerful. See this link ) example: if ( current . operation () == 'insert' && JSUtil . notNil ( current . parent ) && ! current . work_effort . nil ())  option 3 there might be times when you need to get inside the GlideRecord and perform the check there, for example if the code goes down 2 optional routes depending on null / not null can use gs.nil : var grAppr = new GlideRecord ( 'sysapproval_approver' ); var grUser = new GlideRecord ( 'sys_user' ); if ( grUser . get ( 'sys_id' , current . approver )){...

Code a pause/wait - gs.sleep or gs.wait alternative, pause script for specified seconds (timer)

Code a pause/wait - gs.sleep / gs.wait alternative, pause script for specified seconds (timer)  e.g. 10 seconds: do_sleep ( 10000 ); function do_sleep ( milliseconds ) { var start = new Date (). getTime (); for ( var i = 0 ; i < 1e7 ; i ++) { if (( new Date (). getTime () - start ) > milliseconds ){ gs . print ( 'waking up!' ); break ; } } }