【问题标题】:javascript how to run functions with 'when' and 'then'javascript如何使用'when'和'then'运行函数
【发布时间】:2017-12-17 15:36:28
【问题描述】:

我已经在堆栈中搜索过类似的问题,但找不到明确的答案。我有一个小提琴,可以从一个单词中逐个字母地键入。但是当我运行该函数两次时,它会一起执行。我尝试使用 when 和 then 但它似乎仍然不起作用。我希望结果是“Hello, World!Hello2”,但它会一起打印出来,“HHeelllloo....”

http://jsfiddle.net/Jsbbvk/vL8tLwfh/

(一些伪代码)

$.when(showText(param1, param2)).then(function() {
  showText(param3, param4);
});

【问题讨论】:

  • showText(param1, param2) 是做什么的?然后返回 - 哦,我明白了,它返回 undefined ...你知道 $.when 做什么吗?
  • $.when 不会变魔术(这里根本不应该使用它)。您的 showText 函数需要返回一个承诺,该承诺将在动画完成后得到解决。
  • 您的预期结果是什么?
  • 你知道回调是如何工作的吗?如果没有,就从那开始。使用 one 作为showText 的参数,并在if (index < message.length)else 部分调用它 - 即迭代结束时
  • 谢谢Bergi,我已经对此进行了调查,并成功创建了带有回调的showText函数!

标签: javascript jquery .when


【解决方案1】:

我试图解释为什么会发生:

  • 首先调用 $.when(showText(params)) 然后它附加第一个 索引(“H”)到“div”
  • 然后用interval调用setTimeout函数,showText为 再次调用
  • 但是你的 $.when(showText(params)) 不能等到 setTimeout 是 完成,
  • 因此,调用了 $then 方法并运行您的 showText("#msg", "Hello2", 0, 500) 而 showText("#msg", "Hello, World!", 0, 500) 仍在运行 打印“H”后
  • 所以他们两个同时运行,而不是互相等待

我尝试修复您的代码,而不是使用 $.when 和 $.the,我正在使用回调函数。所以回调不会在 setInterval 完成之前调用。

function showText (target, message, index, interval, callback) {
  if (index < message.length) { 
    $(target).append(message[index++]); 
    var session = setTimeout(function () {
    	showText(target, message, index, interval, callback);
      if(index === message.length -1){
      	callback ? callback() : null;
      }
    }, interval); 
  }
}
    
$(function () { 

    showText("#msg", "Hello, World!", 0, 500, function(){
    	showText("#msg", "Hello2", 0, 500)
    })
    
 
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="msg"/> 
<span id="text_target"></span>

我的小提琴: https://jsfiddle.net/firhatsungkar/zg9un4po/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多