How can I pass a parameter to a setTimeout() callback?

前端 未结 28 2323
既然无缘
既然无缘 2020-11-21 07:31

I have some JavaScript code that looks like:

function statechangedPostQuestion()
{
  //alert("statechangedPostQuestion");
  if (xmlhttp.readyState==         


        
28条回答
  •  [愿得一人]
    2020-11-21 07:59

    Replace

     setTimeout("postinsql(topicId)", 4000);
    

    with

     setTimeout("postinsql(" + topicId + ")", 4000);
    

    or better still, replace the string expression with an anonymous function

     setTimeout(function () { postinsql(topicId); }, 4000);
    

    EDIT:

    Brownstone's comment is incorrect, this will work as intended, as demonstrated by running this in the Firebug console

    (function() {
      function postinsql(id) {
        console.log(id);
      }
      var topicId = 3
      window.setTimeout("postinsql(" + topicId + ")",4000); // outputs 3 after 4 seconds
    })();
    

    Note that I'm in agreeance with others that you should avoid passing a string to setTimeout as this will call eval() on the string and instead pass a function.

提交回复
热议问题