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

前端 未结 28 1960
既然无缘
既然无缘 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:18

    this works in all browsers (IE is an oddball)

    setTimeout( (function(x) {
    return function() {
            postinsql(x);
        };
    })(topicId) , 4000);
    
    0 讨论(0)
  • 2020-11-21 08:19

    You can try default functionality of 'apply()' something like this, you can pass more number of arguments as your requirement in the array

    function postinsql(topicId)
    {
      //alert(topicId);
    }
    setTimeout(
           postinsql.apply(window,["mytopic"])
    ,500);
    
    0 讨论(0)
  • 2020-11-21 08:19

    // These are three very simple and concise answers:

    function fun() {
        console.log(this.prop1, this.prop2, this.prop3);
    }
    
    let obj = { prop1: 'one', prop2: 'two', prop3: 'three' };
    
    let bound = fun.bind(obj);
    
    setTimeout(bound, 3000);
    
     // or
    
    function funOut(par1, par2, par3) {
    
      return function() { 
    
        console.log(par1, par2, par3);
    
      }
    };
    
    setTimeout(funOut('one', 'two', 'three'), 5000);
    
     // or
    
    let funny = function(a, b, c) { console.log(a, b, c); };
    
    setTimeout(funny, 2000, 'hello', 'worldly', 'people');
    
    0 讨论(0)
  • 2020-11-21 08:20

    I know its been 10 yrs since this question was asked, but still, if you have scrolled till here, i assume you're still facing some issue. The solution by Meder Omuraliev is the simplest one and may help most of us but for those who don't want to have any binding, here it is:

    1. Use Param for setTimeout
    setTimeout(function(p){
    //p == param1
    },3000,param1);
    
    1. Use Immediately Invoked Function Expression(IIFE)
    let param1 = 'demon';
    setTimeout(function(p){
        // p == 'demon'
    },2000,(function(){
        return param1;
    })()
    );
    
    1. Solution to the question
    function statechangedPostQuestion()
    {
      //alert("statechangedPostQuestion");
      if (xmlhttp.readyState==4)
      {
        setTimeout(postinsql,4000,(function(){
            return xmlhttp.responseText;
        })());
      }
    }
    
    function postinsql(topicId)
    {
      //alert(topicId);
    }
    
    0 讨论(0)
提交回复
热议问题