Posted By

mjsiemer on 08/30/10


javascript closure for setTimeout

Versions (?)

Settimeout with closure in for loop

 / Published in: JavaScript


  1. for (i=0;i<11;i++){
  2. //this will create 11 timers that will alert the value of 'i' at the time
  3. //the timer was created, all to fire after 1 second
  4. //to change what gets alerted, change the "(i)" portion at the end
  5. //can be used with more complex functions by adding to what's after "return"
  6. //can pass in multiple variables by adding to function(x,y,z), putting those
  7. //in proper places w/in the code, and then defining those variables at the end
  8. //ie, "(i,j,k)"
  9. setTimeout(function(x){return function(){alert(x)};}(i),1000);
  10. }

Report this snippet  


RSS Icon Subscribe to comments
Posted By: mjsiemer on August 31, 2010

used: ezpl theme, footer-cta.php

You need to login to post a comment.