首页 > 解决方案 > 2 函数异步结果 2.get,post 函数

问题描述

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 函数是样式的按钮操作,但是要单击非常慢的按钮操作,我想在运行最喜欢 1(id,sender_id)的最后一个结果 favourite2 函数后 3 或 5 秒,超时或异步我该如何解决

favorite2 = (id,sender_id) => {

    // get or post process for favorite1 result
}

标签: javascriptreactjsasynchronous

解决方案


只需使用标准的去抖动功能:

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);
  };
};

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

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

推荐阅读