简体   繁体   English

JavaScript:setTimeout不会在循环内更新值

[英]JavaScript: setTimeout not updating value inside loop

I'm aware of closures, IIFE. 我知道闭包,IIFE。
I've read the other answers (they all point to using IIFE). 我已经阅读了其他答案(它们都指向使用IIFE)。
So why is this not working? 那么为什么这不起作用呢?

  • my image should gradually fade-in (in 2s) 我的图像应该逐渐淡入(在2秒内)
  • it seems like it's only rendering once (with final value) 似乎只渲染一次(具有最终值)
var imgFade = document.getElementById('img-fade');
for(i = 0; i < 100; i++){
  (function(step) {
    setTimeout(function() {
      imgFade.style.opacity = (step/100);
    }, 20);
  })(i);
}

here's the code: https://jsfiddle.net/warkentien2/Lh10phuv/1/ 这是代码: https : //jsfiddle.net/warkentien2/Lh10phuv/1/

EDIT: for future readers 编辑:为将来的读者
consider all answers transitioning from i = 1; to 1 <= 100, i++ 考虑从i = 1; to 1 <= 100, i++过渡的所有答案i = 1; to 1 <= 100, i++ i = 1; to 1 <= 100, i++
so it won't stop rendering at 99% 因此它不会以99%的比例停止渲染

A quick but dirty way is multiplying the 20 by step . 一种快速但肮脏的方法是将20乘以step You create all the timeouts at once, so the ones that are supposed to be executed later have higher delay: 您一次创建所有超时,因此本应稍后执行的超时具有更高的延迟:

var imgFade = document.getElementById('img-fade');
for(i = 0; i < 100; i++){
  (function(step) {
    setTimeout(function() {
      imgFade.style.opacity = (step/100);
    }, step * 20);
  })(i);
}

Heres another solution, applying the fade in one after another: 这是另一个解决方案,一个接一个地应用淡入淡出:

var fade = function(step){
  imgFade.style.opacity = (step/100);
  if(step < 100){
    setTimeout(function(){ fade(++step); }, 20);
  }
};

fade(0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM