Sherwin Flight Sherwin Flight - 3 months ago 13
Javascript Question

Repeat javascript function using multiple variables

I'm not sure how to best explain what I am trying to do, so I'll put together a quick example.

Let's say I have a JavaScript function like this:

function myFunction(){
doSomething('text string here');

I need to repeat this function at a specified interval. I can do that with setTimeout.

However, the text string I need to use is not just one single string, I have three. So my function would kind of look like this:

function myFunction(){
var stringOne = "My first string";
var stringTwo = "My second string";
var stringthree = "My third string";

doSomething(*string variable name here*);

So I need to call the function, let's say every 10 seconds, but each time it runs it needs to use the next text string, in order.

So I need to call:

myFunction, and have it use stringOne.
myFunction, and have it use stringTwo.
myFunction, and have it use stringThree.
And then start back at the first one again.

I could write three separate functions, and tie them together in a loop using setTimeout, but it seems like there should be a better solution.


You could use a closure for the counter.

function myFunction() {
    var counter = 0,
        fn = function () {
            var array = ["My first string", "My second string", "My third string"];
            counter %= array.length;
    return fn;
setInterval(myFunction(), 2000);