使用多个变量重复javascript函数

She*_*ght 1 javascript

我不确定如何最好地解释我想要做的事情,所以我将汇总一个简单的例子.

假设我有一个像这样的JavaScript函数:

function myFunction(){
    doSomething('text string here');
}
Run Code Online (Sandbox Code Playgroud)

我需要以指定的间隔重复此功能.我可以用setTimeout做到这一点.

但是,我需要使用的文本字符串不只是一个字符串,我有三个.所以我的功能看起来像这样:

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

    doSomething(*string variable name here*);
}
Run Code Online (Sandbox Code Playgroud)

所以我需要调用函数,让我们说每10秒,但每次运行它需要按顺序使用下一个文本字符串.

所以我需要打电话:

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.
Run Code Online (Sandbox Code Playgroud)

我可以编写三个单独的函数,并使用setTimeout将它们组合在一个循环中,但似乎应该有一个更好的解决方案.

Nin*_*olz 8

你可以使用一个闭包柜台.

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);
Run Code Online (Sandbox Code Playgroud)