简体   繁体   中英

Function doesn't recognize global variable for play/pause slideshow

I'm trying to create a play/pause button for my javascript slideshow, but the button has stalled my progress because of some scope issues. I toggle between two string values by clicking the element play . While the function slideshow does print out working , it fails to print the state out and execute the function.

Here is the fiddle with the gallery:

Fiddle live example

I would really appreciate your help

var state='play'
slideshow()

pause.onclick=function(){
    console.log(state)
    if (state=='play')
    {
        state='pause'
    }
    else{
        state='play'
    }
}

function slideshow(){
    console.log('working')
    if (state == 'play'){
        console.log('play')
        var pic='<img src="'+ images[slide]+'">'
            gallery.innerHTML=pic
            slide+=1;
            console.log(slide)
            if(slide-1==length){
                slide=0
            setTimeout(slideshow, 3000); 
            }   
        }
    }

Updated fiddle .

Please check the console you could see a not defined error :

Uncaught ReferenceError: slide is not defined(…)

And when you declare the slide variable you'll get :

Uncaught ReferenceError: gallery is not defined(…)

You've to declare the both slide and gallery variables :

var slide=0;
var gallery= document.getElementsByClassName('gallery')[0];

Hope this helps.

I have put a completed fiddle here .

Your slideshow wasn't working initially for a couple of reasons:

  1. Your check for when the slide counter has reached max was incorrect. It needs to be: if(slide==images.length){ .

  2. You had a } in the wrong place. It was only setting the timeout if inside the if .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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