Question

In the following function parameters (from , to) are in px. In the code the codeline : setTimeout('slideLogo(' + from + ',' + to + ')', 75); contains so many plus signs, I am much confused here. In addition to it so many single quote signs(') are also very confusing. Please help me to clear this part.

function slideLogo(from, to) {
             if (from < to) {
                company.top = (from += 10);
                setTimeout('slideLogo(' + from + ',' + to + ')', 75);
            }
            else initObjects();
}
Was it helpful?

Solution

When a plus sign is used and one of the values is a string, the plus sign concantenates the values together as a string, so in this case the strings in the variables are just concantenated into the string passed to setTimeout. Here's an example

var from = '10';
var to   = 40;

var fn   = 'slideLogo(' + from + ',' + to + ')'; // result == "slideLogo(10,40)"

However, passing a string to setTimeout is the same as eval'ing the string, and bad practice.

Preferably it should look like this

function slideLogo(from, to) {
     if (from < to) {

        company.top = (from += 10);
        setTimeout(function() {
            slideLogo(from, to);
        }, 75);

     } else {

        initObjects();

     }
}

OTHER TIPS

if

from = 10 and to = 20

the code would read

function slideLogo(from, to) {
         if (from < to) {
            company.top = (from += 10);
            setTimeout('slideLogo(10, 20), 75);
        }
        else initObjects();

}

the + in the code is used as string concatinator. The ' delimit the hard coded pieces of strings and the + then adds the variables to that string.

As PhistucK has mentioned in the comments, it's considered unsafe to pass in strings to setTimeout. You can either create an anonymous function like this:

setTimeout(function() {
  slideLogo(from, to);
}, 75);

Or, pass in a bound function, like this:

setTimeout(slideLogo.bind(null, from, to), 75);

Cleaned up your code:

function slideLogo(from, to) {
             if (from < to) {
                company.top = (from += 10);
                setTimeout(function() {
                    slideLogo(from, to);
                }, 75);
            }
            else initObjects();
}

The code contains a setTimeout. The first parameter of the setTimeout is an anonymous function calling your slideLogo function, passing the from and to parameters. The second parameter of the setTimeout is the time (75 milliseconds) to wait before the anonymous function is executed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top