tonyf
tonyf

Reputation: 35557

setTimeout usage issues

I have the following JavaScript and I am having issues within using setTimeout, ie:

function setUrl()
{
  // Get system URL details
  var url_path = new String(window.location.pathname);

  var new_url;

  new_url = window.location.host;
  }
  setTimeout("setValue('ONE_UP_URL',new_url);",2000);
}

But for some reason, I am getting the error: 'new_url' is undefined.

How can I call this function using setTimeout?

Upvotes: 0

Views: 1251

Answers (3)

meder omuraliev
meder omuraliev

Reputation: 186562

Try updating it to something like:

function setValue( s, variable ) {
    alert( s );
    alert( variable );
}

function setUrl()
{
  // Get system URL details
  var url_path = window.location.pathname, 
      new_url = window.location.host;

  setTimeout(
    function() {
        setValue('ONE_UP_URL',new_url);
    }, 2000 );
}

Upvotes: 1

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827366

Don't use a string as the first argument of the setTimeout function call, use an anonymous function.

You also had an extra curly brace:

function setUrl() {
  // Get system URL details
  var url_path = window.location.pathname,
      new_url = window.location.host;

  setTimeout(function () {
    setValue('ONE_UP_URL',new_url);
  }, 2000);
}

If you use a string, it will evaluated and that is not really recommended.

Evaluating code by using eval (and its relatives, Function, setTimeout, and setInterval) is considered dangerous, because they will execute the code you pass with the privileges of the caller, and almost all the times there is a workaround to avoid them.

Other minor things:

  • The call to the String constructor in your code is redundant, since window.location.pathname is already a string.
  • You can declare your function variables on a single var statement.

Upvotes: 7

John Fisher
John Fisher

Reputation: 22719

You have a rogue closing brace. Either there is more code missing, or you just need to remove it. (The line above setTimeout.)

Also, you should replace this:

setTimeout("setValue('ONE_UP_URL',new_url);",2000);

with this:

setTimeout(function() { setValue('ONE_UP_URL', new_url); }, 2000);

Upvotes: 6

Related Questions