javascript for 循环中的所有 setTimeouts 一次发生 [英] All the setTimeouts inside javascript for loop happen at once

查看:62
本文介绍了javascript for 循环中的所有 setTimeouts 一次发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此函数应从页面顶部向下滚动到下方 215 像素,并增加延迟,以便第一个 window.scrollTo 事件发生在 10 毫秒,下一个发生在 20 毫秒,依此类推.
最后一行应该延迟 2150 毫秒,所以总共需要大约 2 秒.
相反,它会立即一次性向下滚动 215 个像素.

This function should scroll down from the top of the page to 215 pixels below, with an increasing delay, so that the first window.scrollTo event happens at 10ms, the next at 20ms, and so forth.
The last line should be delayed by 2150 ms so in all it takes about 2 seconds.
Instead, it immediately scrolls down 215 pixels all at once.

function scrollDown() {
  var yFinal=216, delay=0;
  for (y=0; y<yFinal; y++) {
    delay = delay+10
    setTimeout(function() {
      window.scrollTo(100,y);
    },delay);
  }
}

悲伤的脸.为什么?

function showCategory(categoryId)
{
  var yInitial=document.body.scrollTop,
      yFinal=216,
      delay=0;

  if (yInitial<yFinal)
  {
    yInitial=(yFinal-yInitial)/1.3+yInitial;
    window.scrollTo(100, yInitial);

    for (var yCurrent = yInitial; yCurrent < yFinal; yCurrent+=2)
    {
      delay += 30;
      (function(position)
      {
        setTimeout(function()
        {
          window.scrollTo(100, position);
        }, delay);
      })(yCurrent);
    }
  }
}

推荐答案

超时不会同时发生,它们会在您期望的时间发生.但是,它们都尝试滚动到由相同的 y 变量表示的位置,因此它们都使用循环结束时 y 的任何值.

The timeouts don't all happen at once, they happen with the timing you expect. However, they all try to scroll to a position represented by the same y variable, so they all use whatever value y has when the loop finishes.

通常的解决方法是引入一个闭包:

The usual fix for this is to introduce a closure:

function scrollDown() {
    var yFinal = 216,
        delay = 0;

    for (var y = 0; y < yFinal; y++) {
        delay += 10;
        (function(position) {
            setTimeout(function() {
                window.scrollTo(100, position);
            }, delay);
        })(y);
    }
}​

(还要注意,您的 y 变量是全局变量:您应该使用 var 声明它以使其成为本地变量.)

(Note also that your y variable was global: you should declare it with var to make it local.)

这篇关于javascript for 循环中的所有 setTimeouts 一次发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆