1

I'm trying to use multiple variables in a function. This one works for 2 variables, but what if there are 5 sites to get scripts from?

function scripts(url,url2){
            window.setInterval(function (){
                $.getScript(url);
                $.getScript(url2);
                        },10000)
        }

scripts('http://www.site1.com/1.jpg','http://www.site2.com/1.jpg');

What is the correct way to use multiple variables in a function, when we can use as more variables as we can?

2 Answers 2

3

If you want to pass an unknown number of variables you can do it two ways.

  1. pass an array and iterate over the items in it

    function scripts(urls){
        window.setInterval(function (){
            for(var i=0,len = urls.length; i< len; i++){
                $.getScript( urls[i] );
             }
        },10000)
    }
    // pass an array
    scripts(['http://www.site1.com/1.jpg','http://www.site2.com/1.jpg']);
    
  2. use the arguments keyword

    function scripts(){
        var urls = Array.prototype.slice.call(arguments);
        window.setInterval(function (){
            for(var i=0,len = urls.length; i< len; i++){
                $.getScript( urls[i] );
             }
        },10000)
    }
    
    scripts('http://www.site1.com/1.jpg','http://www.site2.com/1.jpg');
    
Sign up to request clarification or add additional context in comments.

2 Comments

Above commenter has added an additional ".call" after the slice. Is there any difference ?
@user198989 yes, it is required. It was an oversight on my part. I have edited my answer to include it.
3

You could use arguments object.

function scripts(){
    var args = Array.prototype.slice.call(arguments);
    window.setInterval(function (){
        // then use a loop for args.

    }, 1000)
}

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.