Sherwin Flight
Sherwin Flight

Reputation: 2363

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.

Upvotes: 1

Views: 957

Answers (5)

Redu
Redu

Reputation: 26161

No need for closures whatsoever; Not mentioned but i have also added a timeout. Just do like this;

var array = ["My first string", "My second string", "My third string"],
      sid;
function runner(i){
  console.log(array[i=i%array.length]); // i hate i growing indefinitely
  sid = setTimeout(_ => runner(++i),2000);
}

runner(0);
setTimeout(_ => clearTimeout(sid),20000);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

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"];
            console.log(array[counter]);
            counter++;
            counter %= array.length;
        };
        fn();
    return fn;
}
setInterval(myFunction(), 2000);

Upvotes: 8

adeneo
adeneo

Reputation: 318182

Use a recursive function with incrementing index

(function myFunction(i){
   var arr = ["My first string", "My second string", "My third string"];
   
   setTimeout(function() {
       doSomething( arr[i = i < arr.length ? i : 0] );
       myFunction(++i);
    }, 1000);
})(0);

function doSomething(str) {
    console.log(str)
}

Upvotes: 0

synthet1c
synthet1c

Reputation: 6282

function myFunction(strings){
  var ii = 0
  function iterate(){
    // increment or reset the iterator
    doSomething(strings[ii++ % strings.length])
    // call it again after 1 second (change this)
    setTimeout(iterate, 1000)
  }
  // kick off the iteration of your strings
  iterate()
}

function doSomething(val) {
  console.log(val)
}

// init the iterator with your strings
myFunction([
 'myFunction, and have it use stringOne.',
 'myFunction, and have it use stringTwo.',
 'myFunction, and have it use stringThree.'
])

Upvotes: 1

JohnnyAW
JohnnyAW

Reputation: 2876

just use a global variable to track the current string:

currentString = 0;

then after each call increase the value and modulo it:

function myFunction(){
    switch(currentString){
    //print the current string
    }

    currentString = (currentString + 1) % 3;
}

Upvotes: 1

Related Questions