gpt4 book ai didi

javascript - 如何仅在执行第一个方法后才执行第二个方法

转载 作者:行者123 更新时间:2023-11-28 03:03:34 25 4
gpt4 key购买 nike

我只想在加载段落标签后打印标题标签。下面是我的 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);
});

最佳答案

我会做这样的事情(请注意,Internet Explorer 不支持 ES6 Promise,但也有一些垫片可以在旧浏览器中使用 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);
});
});

关于javascript - 如何仅在执行第一个方法后才执行第二个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33595179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com