我正在尝试在我的 promise 范围内设置一个计时器。它们似乎都立即返回,而我尝试创建的计时器实际上并没有增加返回之间的时间 所有函数一次返回,我需要它们在时间上间隔开,例如:函数 1(等待 4 秒)函数 2(等待 4 秒)等。
我试过用
.then(()=>{
let counter=0
while(counter < 6000){
counter+=1
}
this.props.toggleMenu()
})
这是我当前的示例,它调用需要在我的应用程序中一次执行一个的多个函数
rundemo=()=>{
//function is designed to run all the essential functions in the app one after another
const wait = time => new Promise((resolve) => setTimeout(resolve, time));
var docvalue= document.getElementById('regex-example').value
var selection = this.range(0,20,docvalue)//get selected chars in element
var selectedText = selection.toString(); //sends the elements to a string
wait(6000).then(() => this.props.setHighlightMode() )
.then(()=>{
let counter=0
while(counter < 6000){
counter+=1
}
this.props.toggleMenu()
})
.then(()=>{
let counter=0
while(counter < 6000){
counter+=1
}
this.props.openNotes()
})
.then(()=>{
let counter=0
while(counter < 6000){
counter+=1
}
this.props.close()
})
.then(()=>{
let counter=0
while(counter < 6000){
counter+=1
}
this.props.setScholarMode()
})
.then(()=>{
let counter=0
while(counter < 6000){
counter+=1
}
this.props.DemosynonymsFunction("noun")
})
}
最佳答案
你已经有了一个 wait
函数,而不是使用 while
等待,你可以下巴这些 promise :
rundemo = () => {
//function is designed to run all the essential functions in the app one after another
const wait = time => new Promise(resolve => setTimeout(resolve, time));
var docvalue = document.getElementById("regex-example").value;
var selection = this.range(0, 20, docvalue); //get selected chars in element
var selectedText = selection.toString(); //sends the elements to a string
wait(6000)
.then(() => this.props.setHighlightMode())
.then(wait(6000))
.then(() => this.props.toggleMenu())
.then(wait(6000))
.then(() => this.props.openNotes())
.then(wait(6000))
.then(() => this.props.close())
.then(wait(6000))
.then(() => this.props.setScholarMode())
.then(wait(6000))
.then(() => this.props.DemosynonymsFunction("noun"));
};
如果这些函数不返回 promisese,将它们链接起来:
wait(6000)
.then(() => this.props.setHighlightMode())
.then(() => wait(6000).then(() => this.props.toggleMenu()))
.then(() => wait(6000).then(() => this.props.openNotes()))
.then(() => wait(6000).then(() => this.props.close()))
.then(() => wait(6000).then(() => this.props.setScholarMode()))
.then(() => wait(6000).then(() => this.props.DemosynonymsFunction("noun")));
关于javascript - 为 promise 设置计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58188223/