JavaScript Closure

19. July 2016 10:24

 

I’ve heard a lot about closure in JavaScript but until recently didn’t see a good example that made sense to me. In the Pluralsight course Advanced JavaScript by Kyle Simpson I think I finally found it. It starts with a definition:

 

Closure is when a function “remembers” its lexical scope.

 

In this example, the inline function passed to set timeout “remembers” its lexical scope. It always refers to the variable declared outside of its definition. The value at the time the function executes is always 6 (the loop has completed before the first invocation).

 

for(var i = 1; i <= 5;i++) {
    setTimeout(function(){
      console.log("i = " + i);
  }, i*1000);
}

 

So, that led me to wonder how can we get the iterated value logged instead? Instead of an inline function, pass a function to set timeout. Now the value of the variable is passed to the log function and you get the iterated value (1, 2, 3, 4, 5).

 

for(var i = 1; i <= 5;i++) {
      setTimeout(log(i), i*1000);
}

function log(x){
    console.log("x = " + x);
}

 

Here is a fiddle.

Windows Server 2012 Terminal Services Manager Options

11. July 2016 15:04

 

Invariably with our development servers someone will forget they are logged on, get disconnected and leave an unused Terminal Services session. One two people have done this, no one else can get logged in via RDP. In the good old days there was a nice gui tool available under admin tools – Terminal Services Manager. It is not there in Server 2012. However there are some command line tools available.

qwinsta – can be used to display the current RDP sessions.

C:\WINDOWS\system32>qwinsta /server:oma01tstade06
SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
services                                    0  Disc
console                                     1  Conn
rdp-tcp#48        htpham                    2  Active
rdp-tcp#49        costws                    3 Active
31c5ce94259d4...                        65536  Listen
rdp-tcp                                 65537  Listen

rwinsta – used to delete a session (specifying the ID number retrieved from the query).

C:\WINDOWS\system32>rwinsta /server:oma01tstade06 3

About the author

I'm a .NET developer, a husband and a father of three beautiful girls.

Month List