![](/img/trans.png)
[英]Wait Until setTimeout is Complete Before Returning Value Javascript
[英]Wait for function that makes use of settimeout to complete in javascript before rerunning it
请协助。
我需要wait
操作完成才能在javascript中再次执行它。 这些操作可能在不同的时间运行。 并非一次全部。 我一次运行2个操作有一个问题,因为它们同时执行。
输出应使用settimeout
在“ textarea”中附加文本。 它需要等待完成,然后在调用“ arrayofrandomtext”数组的任意索引处开始键入下一个文本。 稍后仍然可以基于按键等调用“ ProcessText(someint)”。
var index=0; var arrayofrandomtext = ["Hello World","something else", "other stuff"]; function ProcessText(someint){ //These may run together next_letter(arrayofrandomtext[someint]); //wait to complete and rerun it with other text next_letter(arrayofrandomtext[someint]); //later on if the user hits a key this may run only next_letter(arrayofrandomtext[someint]); } function next_letter(text){ if (index <= text.length) { someControl.value = text.substr(0, index++); setTimeout(function () { next_letter(text); }, 50); } }
尝试创建文本值数组,使用Array.prototype.slice()
创建文本值初始数组的副本; Array.prototype.shift()
设置next_letter
文本参数; 如果数组在对next_letter
初始调用之后具有.length
,则递归调用ProcessText
var arr = ["Hello...", "Some other text"], copy = arr.slice(), button = document.querySelector("input") someControl = document.querySelector("textarea"), index = 0; function ProcessText() { next_letter(copy.shift()) } function next_letter(text) { if (index <= text.length) { someControl.value = text.substr(0, index++); setTimeout(function() { next_letter(text); }, 50); } else { index = 0; if (!!copy.length) { ProcessText() } else { copy = arr.slice(); } } } button.onclick = ProcessText;
<input type="button" value="click" /><br /> <textarea></textarea>
首先,您已经完成了此操作-但我想要一个工作版本进行演示。 您可以编写一个递归函数,该函数在完成后对其自身调用settimeout。 例如,给定一个注销字符串中每个字母的函数。
var log = function(text, index, duration) {
console.log(text[index]);
if (index < text.length - 1) {
setTimeout(function() {
log(text, index + 1, duration);
}, duration);
}
};
log("Hello There", 0, 1000);
log("Nice to see You", 0, 1000);
当然,现在,如果您运行此代码,第二个日志功能将不会等待第一个。 您可以使用Promises和/或Callbacks执行异步控制流。 首先修改log函数以将回调作为参数。
var logCB = function(text, index, duration, cb) {
console.log(text[index]);
if (index < text.length - 1) {
setTimeout(function() {
logCB(text, index + 1, duration, cb);
}, duration);
} else {
cb(); //execute callback
}
};
现在,如果您传递了第二个函数(包装在另一个函数中以延迟执行)。 作为您的第一个参数,它将在完成后执行。
var cb = function() {
logCB("Nice to see you", 0, 1000);
};
logCB("Hello, World!", 0, 1000, cb);
虽然这可行,但对于多个嵌套来说却变得笨拙。 更好的解决方案是使用promise-您只需要将logCB包装到另一个函数中即可。 这里f是一个logCB。
var promiseLog = function(f, text, delay) {
return new Promise(function(resolve, reject) {
f(text, 0, delay, resolve);
});
};
然后...我们可以将它们链接在一起,以..然后等待完成。
promiseLog(logCB, "Hello World", 1000)
.then(function() {
return promiseLog(logCB, "Hey There", 1000)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.