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

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

I have some JavaScript code that looks like:

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


        
28条回答
  •  余生分开走
    2020-11-21 08:17

    As there is a problem with the third optonal parameter in IE and using closures prevents us from changing the variables (in a loop for example) and still achieving the desired result, I suggest the following solution.

    We can try using recursion like this:

    var i = 0;
    var hellos = ["Hello World1!", "Hello World2!", "Hello World3!", "Hello World4!", "Hello World5!"];
    
    if(hellos.length > 0) timeout();
    
    function timeout() {                
        document.write('

    ' + hellos[i] + '

    '); i++; if (i < hellos.length) setTimeout(timeout, 500); }

    We need to make sure that nothing else changes these variables and that we write a proper recursion condition to avoid infinite recursion.

提交回复
热议问题