Domanda

i am creating a simple fadein effect using pure javascript. For this i have tried three methods. M1 is using recursive functionality and M2 is based on for loop and anonymous function and M3 is based on for loop and string based function call.

Under M1 the code is giving perfect output as a fadein effect.

But under M2 the fadein effect does not work and the content directly goes visible after a specified duration.

Now again under M3 the fadein effect is generated.

Can anyone guide me that how to generate fadein effect based on M2. Means using for loop and anonymous function call.

M1------ Works perfectly------ http://jsfiddle.net/TH2dn/7/

function starter(){
    var i = 0;
    var el = document.getElementById("div1");
    fadeIn(el,i);
}

function fadeIn(el,i) {

    i = i + 0.01;
    seto(el,i);
    if (i<1){setTimeout(function(){fadeIn(el,i);}, 10);}
}

function seto(el,i)
{
    el.style.opacity = i;
}

starter();

M2------Does not work------ http://jsfiddle.net/TH2dn/13/

function starter(){
    var i = 0;
    var el = document.getElementById("div1");
    fadeIn(el,i);
}

function fadeIn(el,i) {

    for ( i = 0 ; i<=1 ; i = i + 0.01){
    setTimeout( function(){ seto(el,i); } , i * 1000);}
}

function seto(el,i)
{
    el.style.opacity = i;
}

starter();

While using JSHint in the JSFiddle on M2 it says that --" Don't make functions within a loop "

M3------Works Properly------ jsfiddle.net/TH2dn/9/

var i = 0;
var el = document.getElementById("div1");

function fadeIn() {
    for ( i = 0 ; i<=1 ; i = i + 0.01){
        setTimeout("seto(" + i + ")", i * 1000);
    }
}

function seto(i)
{
    el.style.opacity = i;
}

The abopve question is based on Pure JavaScript fade in function

È stato utile?

Soluzione

it says that --" Don't make functions within a loop "

That's good advice, but it isn't your (main) problem here.

Your problem is that you are invoking every functions 1 second from right now. They will execute in a random order, starting in 1 second and firing as fast as they can.

Do this:

function fadeIn(el) {
    var go = function(j) {
       setTimeout( function(){ seto(el,j); } , j *1000);}
    };

    for (var i = 0 ; i<=1 ; i = i + 0.01) go(i);
}

Altri suggerimenti

Below is the complete answer to the question...

ANS2 --- DEMO

function fin(){
    var i = 0;
    var el = document.getElementById("div1");
    fadeIn(el,i);
}

function fadeIn(el,i) {
    var go = function(i) {
        setTimeout( function(){ seto(el,i); } , i * 1000);
    };
    for ( i = 0 ; i<=1 ; i = i + 0.01) go(i);
}

function seto(el,i)
{
    el.style.opacity = i;
}

Thanks to Malvolio

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top