开发者

setTimeout usage issues

I have the following JavaScript and I am having issues within using s开发者_C百科etTimeout, 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?


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜