I want to make slide show with js using setinterval function but i don’t know why my code not working . while there is no error in console . i have number of pictures named start with bk then followed by number and i call there pictures by if statement in function but slide still not working stop at bk1 here is my code if you could help me by explain how setinterval Works
<script>
function slides(sf)
{
sf=sf+1;
document.getElementById("centerd").style.backgroundImage = "url(pics/bk"+sf+".png)";
if(sf>2)
{
sf=1;
}
}
setInterval(slides(0),3000);
</script>
also i tried with for loop
<script>
function slides()
{
for(var i=0;i<3;i++)
{
document.getElementById("centerd").style.backgroundImage = "url(pics/bk"+i+".png)";
if(i==2)
{
i=1;
}
}
}
setInterval(slides,3000);
</script>
but not working too
2
Answers
In your first one
This is eqivalent to calling
As slides is evaluated and returns nothing
In #2, your loop will run before giving the UI a chance to update. The UI can only update after you have left the function, as the UI is using the same thread. You probably want to keep your counter value either in the function (via
this.x
or set up a var / field underwindow
to track where in your animation you are.At a glance I’m seeing a couple of things wrong here.
First, this doesn’t do what you think it does:
This calls
slides(0)
immediately and once, then tries to call the result of that function (which isundefined
) every three seconds.Additionally, this variable only ever has a value of
1
:Because
sf
is declared and exists only within the scope of that function, and you only ever call the function with the value0
. So every time the function runs (if you were to call it again successfully),sf
would only ever have a value of1
after the above operation.Fix both of these things. First, remove
(0)
from the function call insetInterval
so it calls the function each time, not the result of the function:Then declare
sf
outside the function so changes to it persist across multiple calls to the function: