1

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.

1
  • Use an array!!! Commented Oct 10, 2016 at 11:54

5 Answers 5

8

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);

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

16 Comments

Out of curiosity, what was the reason for your last code change? The code you had posted previously seems to be working? One further question, how would I get that function to run immediately the first time, and then at the specified interval after that?
You can use setTimeout with recursion
@Nina, by any chance have you used array.entries? How do you reset iterator to 0? Sample Fiddle
@Rajesh, while i am a great fan of recursions, setInterval works better for fixed invervals than setTimeout and countinuous calls, because it does not uses the stack more than necessary.
@NinaScholz Where do you get this much knowledge from. Do you take apprentice? But jokes apart, really appreciate you taking time to explain things.
|
1

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;
}

1 Comment

yeah, true that:)
1

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.'
])

3 Comments

why would you reinvent modulo?
Cool didn't think of that. Much cleaner
you should still use strings.length
0

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)
}

6 Comments

Keep in mind that setTimeout evaluates the passed string inside. Bad for concerning security sides.
@bash0ne - why would setTimeout evaluate anything, unless you pass it a string ?
@bash0ne - true story how? Do you still think this evaluates the code inside the timeout ?
It is possible to pass the setTimeout function a string in the first parameter which must go through eval(). So yes
I'm not passing a string, but an anonymous function, so how is that even remotely relevant ?
|
0

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);

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.