首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >2函数异步结果2. get、post函数

2函数异步结果2. get、post函数
EN

Stack Overflow用户
提问于 2018-11-08 09:21:38
回答 2查看 52关注 0票数 0

2运行我的按钮操作的函数

代码语言:javascript
复制
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秒后运行favorite2函数,用于favorite1 (id,sender_id)、超时或asyn,如何解决此问题?

代码语言:javascript
复制
favorite2 = (id,sender_id) => {

    // get or post process for favorite1 result
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-11-08 10:19:48

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

代码语言:javascript
复制
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);
}
票数 1
EN

Stack Overflow用户

发布于 2018-11-08 10:27:00

您可以使用异步等待。

代码语言:javascript
复制
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); 

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53204716

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档