timer - javascript timeout in loop -


i'm learning javascript fun, , having weird problem. i'm trying create own fade-in function. however, code doesn't work, shows "content" div in full opacity.

the setcontentopacity function does work, i've tested , works charm.

ideally think should happening 1000 "settimeout" calls should placed on "stack", first 1 setting opacity low no timeout, second 1 setting opacity little higher small timeout, way last call sets opacity 1000 3000 timout.

so basically, should setting opacity 0 right away, ~333 in 1 second, ~666 in 2 seconds, , 1000 in 3 seconds. think logic sound here; calls setting opacity should resolve in manner on time creates fade in effect.

so here's relevent code:

<script language='javascript' type='text/javascript'>  //takes value 0-1000 function setcontentopacity(value) {    document.getelementbyid('content').style.opacity = value/1000;    document.getelementbyid('content').style.filter = 'alpha(opacity=' + value/10 + ')'; }  function fadeincontent(){  setcontentopacity(0);  (var i=0;i<=1000;i++) {    settimeout(function(){setcontentopacity(i);}, (i*3)); }   }  onload=fadeincontent;  </script> 

(note: tried calling settimeout(setcontentopacity(i), (i*3));, didn't seem work, , got better results using anonymous function)

any idea what's wrong here? in advance!

you need capture value of i when assigning settimeout.

try this

for (var i=0;i<=1000;i++) {    (function(ind) {        settimeout(function(){setcontentopacity(ind);}, (ind*3));     })(i); } 

as know scope of variable function scoped. , same value of i shared callbacks of settimeout. value of 1000 . looks if had no effect, because value of variable scoped last iteration shared same common scope. . enclosing in immediately invoked function expression creating new function value of i scoped it.

check fiddle


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -