繁体   English   中英

仅在执行第一种方法后如何执行第二种方法

[英]how to execute second method only after first method is executed

我只想在加载段落标签后才打印标题标签。 以下是我的Javascript代码。 有关更多说明,请参阅插件: http ://embed.plnkr.co/aheHkSQUBft5A4Z3wkie/preview

function changeText(cont1, cont2, speed){
    var Otext = cont1.text();
    var Ocontent = Otext.split("");
    var i = 0;

    function show() {
        if (i < Ocontent.length) {      
            cont2.append(Ocontent[i]);
            i = i + 1;
        };
    };

    var Otimer = setInterval(show, speed);  
};

$(document).ready(function() {
    changeText($("p"), $(".p2"), 30);
    clearInterval(Otimer);
});

$(document).ready(function() {
    changeText($("h2"), $(".h2"), 30);
    clearInterval(Otimer);
});

我会做这样的事情(请注意Internet Explorer不支持ES6 Promises,但也有一些垫片也可以在旧的浏览器中使用Promises)。

您必须填写注释的部分才能使其正常运行:

var Otimer;

/*@TODO: refactor show() function to use ES6 Promises (eventually with shims) */
function show(Ocontent) {
    var i = 0;

    if (i < Ocontent.length) {
        cont2.append(Ocontent[i]);
        i = i + 1;
    };

    if (Otimer === undefined) {
        Otimer = setInterval(show, speed); // Remember to fulfill the promise and remove the interval once it's finished
    }

    // return the promise
};

function changeText(p1, p2, speed) {
    var Otext = p1.text();
    var Ocontent = Otext.split("");

    return show(Ocontent);
};

$(function () {
    changeText($("p"), $(".p2"), 30).then(function() { // We call changeText the second time after the  promise return by changeText() is fulfilled and the show() function has finished
        Otimer = undefined;
        changeText($("h2"), $(".h2"), 30);
    });
});

首先,声明函数内部的变量是作用域变量,您不能从函数外部访问该变量。 所以这行clearInterval(Otimer); 永远行不通。

下面的代码是范围问题的固定代码,并使用回调实现所需的代码。

function changeText(cont1, cont2, speed, cb) {
  var Otext = cont1.text();
  var Ocontent = Otext.split("");
  var i = 0;

  function show() {
    if (i < Ocontent.length) {
      cont2.append(Ocontent[i]);
      i++;
    }else{
      clearInterval(Otimer)
      if(cb) cb()
    }
  };
  var Otimer = setInterval(show, speed);
};

$(document).ready(function() {
  changeText($("p"), $(".p2"), 30, function(){
    changeText($("h2"), $(".h2"), 30);
  });
});

http://plnkr.co/edit/xowItFUWqI79obi4ZVNV?p=preview

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM