-2

-so i am obviously trying to get two functions to run automatically whilst on a timer using setTimeout. However i am not to sure how it works. All i can see when i search it up is it in a function. so how do i have it outside a function?

function ChangeImage() {
    if(position < TrafficL.length) {
    document.getElementById("myImage").src = TrafficL[position];
    position++
    }
}
function RestartPos() {
    if (position==3)
    document.getElementById("myImage").src = TrafficL["position"]
    position=0


    var setTimeout = (ChangeImage(),1500)
    var setTimeout = (RestartPos(),6000) 

1 Answers1

0

You sould call setTimeout as a function:

setTimeout(ChangeImage,1500);
setTimeout(RestartPos,6000);

ChangeImage and RestartPos are like variables referencing a function. If you place parentheses behind them means, you are calling them immediately, but you want to call them after a given time.

You can store the value return by setTimeout() in a variable though, but it's only for cancelling the countdown later:

// nothing happens, because the timeout was cancelled in 1.5s
var t = setTimeout(ChangeImage,1500);
clearTimeout(t);
balping
  • 7,518
  • 3
  • 21
  • 35