[removed] how to pass different object to setTimeout handlers created in a loop?

前端 未结 2 1954
春和景丽
春和景丽 2020-12-10 23:01

I\'m trying to write some JS replicating jQuery\'s fadeIn and fadeOut functions. Here\'s the code I have so far:

function fadeIn(elem, d, callback)
{

    va         


        
2条回答
  •  眼角桃花
    2020-12-10 23:37

    Your first approach is evaluating code at runtime. You are most likely right about why it's failing (elem is not in the scope in which the code is eval'd). Using any form of eval() (and setTimeout(string, ...) is a form of eval()) is a general bad idea in Javascript, it's much better to create a function as in your second approach.

    To understand why your second approach is failing you need to understand scopes and specifically closures. When you create that function, it grabs a reference to the i variable from the fadeIn function's scope.

    When you later run the function, it uses that reference to refer back to the i from fadeIn's scope. By the time this happens however, the loop is over so you'll forever just get i being whatever it was when that loop ended.

    What you should do is re-engineer it so that instead of creating many setTimeouts at once (which is inefficient) you instead tell your setTimeout callback function to set the next Timeout (or you could use setInterval) and do the incrementing if your values inside that callback function.

提交回复
热议问题