2015-11-08 108 views
2

我想在加载段落标记后才打印标题标记。以下是我的Javascript代码。见plunker更多的澄清: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); 
}); 
+0

FYI有没有需要两个'document.ready'处理程序 - 在一个加入两个代码块。 –

+1

@ chetan:打开Web控制台,它提供了重要的信息。 –

+1

@chetan,你可以试试这个回调函数。另外,如果你只使用'Otimer',你可以使用'setTimeout'。 – Rajesh

回答

0

我会做这样的事情(请不是ES6承诺不通过Internet Explorer支持,但也有垫片使用与旧的浏览器承诺过)。

你必须填写注释的部分得到它的工作虽然:

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

首先,变量的函数内声明的范围的变量,你不能从功能的外部访问。 所以行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