简体   繁体   中英

how to execute second method only after first method is executed

I want to print a heading tag only after a paragraph tag is loaded. Below is my Javascript code. See the plunker for more clarification: 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);
});

I would do something like this (please not that ES6 Promises aren't supported by Internet Explorer, but there are shims to use Promises with old browsers too).

You'll have to fill out the parts commented to get it to work though:

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

first of all, variable declaring inside of function is scoped variable, which You cannot access from outside of the function. so the line clearInterval(Otimer); never works.

the code below is fixed code of the scope issue and using callback to implement what you want.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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