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

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

I have some JavaScript code that looks like:

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


        
28条回答
  •  猫巷女王i
    2020-11-21 07:55

    setTimeout is part of the DOM defined by WHAT WG.

    https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html

    The method you want is:—

    handle = self.setTimeout( handler [, timeout [, arguments... ] ] )

    Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler.

    setTimeout(postinsql, 4000, topicId);
    

    Apparently, extra arguments are supported in IE10. Alternatively, you can use setTimeout(postinsql.bind(null, topicId), 4000);, however passing extra arguments is simpler, and that's preferable.

    Historical factoid: In days of VBScript, in JScript, setTimeout's third parameter was the language, as a string, defaulting to "JScript" but with the option to use "VBScript". https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa741500(v%3Dvs.85)

提交回复
热议问题