1

I want to execute a function every specified seconds, and it should loop forever. When the function is finished I want to start a new setTimeout using a random generated value between 2 and 5 (represents seconds).

Maybe badly explained but..

this is what I have so far.

function Start() {
    let count = $("section.mosaic").find("a.item").length;

    ChangePic();

    setTimeout(function () {
        let interval = CREATOR.PUB.Utility.randomInterval(2, 5);

        console.log(interval);

    }, 3000);

    function ChangePic() {

    }
}
2
  • Is ChangePic the function that is supposed to be called every few seconds? Commented Dec 16, 2018 at 7:10
  • @Hydrothermal yes correct Commented Dec 16, 2018 at 7:16

1 Answer 1

2

Move the interval code into ChangePic so that it can call itself when it finishes.

function Start() {
    let count = $("section.mosaic").find("a.item").length;

    ChangePic();

    function ChangePic() {
        // do stuff here

        let interval = CREATOR.PUB.Utility.randomInterval(2, 5);
        setTimeout(ChangePic, interval * 1000);
    }
}

Note that this will call ChangePic once immediately when Start runs, and the random intervals will begin thereafter. If you need the initial execution to be on a delay as well, you could either copy the timeout code and run it instead of calling ChangePic();, or move it into a helper function that you call both inside Start and ChangePic.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.