2函数异步结果2. get,post函数

时间:2018-11-08 09:21:39

标签: javascript reactjs asynchronous

运行我的按钮动作的2个功能

favorite1 = (id,sender_id) => {

    if(this.state["like"+id]==true){
            this.setState({["like"+id]:false})
        }else{
            this.setState({["like"+id]:true})}


     //async or timeout how run 3-5 second for last result ----> this.favorite2(id,sender_id)
}

favorite1函数是用于样式的按钮动作,但是要非常缓慢地单击很多按钮,我想在运行最后一个结果后3或5秒,以便进行favourite1(id,sender_id)的超时2超时或asyn我该怎么办?

favorite2 = (id,sender_id) => {

    // get or post process for favorite1 result
}

2 个答案:

答案 0 :(得分:1)

只需使用标准的反跳功能:

function debounce(func, threshold, execAsap) {
  var timeout = null;
  return function() {
    var obj = this, args = arguments;
    if (timeout) {
      clearTimeout(timeout);
    } else if (execAsap) {
      func.apply(obj, args);
    }
    timeout = window.setTimeout(function() {
      if (!execAsap) {
        func.apply(obj, args);
      }
      timeout = null;
    }, threshold || 200);
  };
};

favorite2D3000 = debounce(favorite2, 3000); // 3000 miliseconds

favorite1 = (id,sender_id) => {
   favorite2D3000(id,sender_id);
}

答案 1 :(得分:1)

您可以使用async-await

async favorite1 = (id,sender_id) => {
         if(this.state["like"+id]==true){
            this.setState({["like"+id]:false})
        }else{
         this.setState({["like"+id]:true}
        }

     //async or timeout how run 3-5 second for last result ----> this.favorite2(id,sender_id)  
     // waits for 5 second
     let result = await favorite2(id,sender_id);

}

favorite2 = (id,sender_id) => {
    setTimeout(function(){

    // get or post process for favorite1 result
    }, 5000); 

}