简体   繁体   English

为什么添加后参数会停止功能

[英]Why Parameter Stops Function When Added

I have a code which I am trying to execute using a parameter in the function, ie - 我有一个正在尝试使用函数中的参数执行的代码,即-

function startFadeEffect(elem){ };

I have made the elem equal to a variable b in the global scope, where b is an array of images. 我已经使elem等于全局范围内的变量b,其中b是图像数组。 Meaning - 含义-

var elem = b[imgNumb];

imgNumb is a variable which is globally "0" and inside a function is defined as imgNumb是一个全局变量为“ 0”的变量,在函数内部定义为

imgNumb = imgNumb + count;

Now, my current code "without" the parameter works perfect - 现在,我当前的代码“不带”参数可以正常使用-

function startFadeEffect(){
    var opacSetting = noOpac / 10;
    b[imgNumb].style.opacity = opacSetting; 
    b[imgNumb].style.display = "block";
    noOpac++;
    if(noOpac < 0){
        opacSetting = 0;    
    }
    if(opacSetting == 1){
        clearTimeout(timer);
        b[imgNumb].style.opacity = 1;
        noOpac = 0;
        return false;
    }
    var timer = setTimeout(startFadeEffect, 75);
}

However, when I use the parameter like this it does not work for me :( 但是,当我使用这样的参数时,它对我不起作用:(

function startFadeEffect(elem){
    var opacSetting = noOpac / 10;
    elem.style.opacity = opacSetting;   
    elem.style.display = "block";
    noOpac++;
    if(noOpac < 0){
        opacSetting = 0;    
    }
    if(opacSetting == 1){
        clearTimeout(timer);
        elem.style.opacity = 1;
        noOpac = 0;
        return false;
    }
    var timer = setTimeout(startFadeEffect(elem), 75);
}

Please note I have already defined the elem variable in the global scope of the file. 请注意,我已经在文件的全局范围内定义了elem变量。 Also, I am only looking for a JS solution no library like JQuery! 另外,我只是在寻找JS解决方案,没有像JQuery这样的库! Thanks 谢谢

This part is incorrect: 这部分不正确:

setTimeout(startFadeEffect(elem), 75);

It should be: 它应该是:

setTimeout(function () {
    startFadeEffect(elem);
}, 75);

setTimeout expects a function as it's first argument. setTimeout需要一个函数作为它的第一个参数。 startFadeEffect(elem) is executed immediately (and doesn't return a function). startFadeEffect(elem)立即执行(并且不返回函数)。 So what happens is that startFadeEffect calls itself recursively until opacSetting == 1 which breaks the recursion. 因此,发生的情况是startFadeEffect递归调用自身,直到opacSetting == 1破坏了递归。

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

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