M.nat
M.nat

Reputation: 13

changing variable inside a function

I'm trying to change src attribute of an image then restore the default value using setInterval()method but it seems that if I use the variable inside the function it doesn't work properly and It must be outside the function, why the variable value wont change inside the function?

var Img1 = document.getElementById('img1');

setInterval(function(){
    var boolean= true;
    if(boolean){
        Img1.src = "pic1.jpg";
        }else{
        Img1.src = "default.jpg";
    }
    boolean= !boolean;
} , 3000);



// This one work properly!

var Img1 = document.getElementById('img1');
var boolean= true;

setInterval(function(){

    if(boolean){
        Img1.src = "pic1.jpg";
        }else{
        Img1.src = "default.jpg";
    }
    boolean= !boolean;
} , 3000);

Upvotes: 0

Views: 92

Answers (2)

Duly Kinsky
Duly Kinsky

Reputation: 996

That is because boolean is always true whenever the function get called. That is the first thing the function does, set boolean to true:

var boolean= true;

boolean does not get modified inside the function until after you check to see which src to choose. Thus, your condition always arrive to the same outcome, which is to set Img.src to pic1.jpg. Hope that helps!

Upvotes: 1

faruh.paerhati
faruh.paerhati

Reputation: 13

Within the function sent to setInterval(), you are setting "boolean" to be true at the start of every iteration of the function. Thus the following code will always set Img1.src = "pic1.jpg"; and the line Img1.src = "default.jpg"; will never get run because "boolean" is true in every case of the iteration.

setInterval(function(){
    var boolean= true;
    if(boolean){
        Img1.src = "pic1.jpg";
    }else{
        Img1.src = "default.jpg";
    }
    boolean= !boolean;
} , 3000);

You want to wrap your setInterval in a function so that you can modify the boolean value per iteration and that the value setDefault is scoped to the caller. For instance:

const IMAGE_DEFAULT = "default.jpg";
const IMAGE_PIC1 = "pic1.jpg";

function StartImageInterval(img) {
    var setDefault = true;

    setInterval(function() {
        img.src = ((setDefault) ? IMAGE_DEFAULT : IMAGE_PIC1);
        setDefault = !setDefault;
    }, 3000);
}

You should then be able to call this function with

var Img1 = document.getElementById('img1');
StartImageInterval(Img1);

Upvotes: 0

Related Questions