gpt4 book ai didi

javascript - 如何在javascript中暂停递归函数3秒?

转载 作者:行者123 更新时间:2023-12-03 03:50:57 25 4
gpt4 key购买 nike

在写这篇文章之前,我已经看到了下面引用的问题。

how-to-pause-a-settimeout-call

how-to-pause-a-settimeout-function

how-to-pause-a-function-in-javascript

delay-running-a-function-for-3-seconds

问题

我有下面的代码,我想要在 setTimeout 函数暂停一段时间后使用它。然后重新继续。

 typingCallback(that) {
let total_length = that.typewriter_text.length;
let current_length = that.typewriter_display.length;
if (that.rewind === false)
{
if(total_length == current_length)
{
// Here I want to pause this function for 3 seconds
clearTimeout(3000);
that.rewind = true;
}
else
{
that.typewriter_display += that.typewriter_text[current_length];
console.log('Loop#1: ' + that.typewriter_display + " " + 'Length' + current_length);
}
}
else if (that.rewind === true)
{
if(current_length == 0)
{
that.rewind = false;
}
else
{
that.typewriter_display = that.typewriter_display.slice(0, -1);
console.log('Loop#2: ' + that.typewriter_display + " " + 'Length' + current_length);
}
}
setTimeout(that.typingCallback, 75, that);
}

最佳答案

基本上一个简单的 setTimeout 就可以做到:

typingCallback(that) {
let total_length = that.typewriter_text.length;
let current_length = that.typewriter_display.length;
if (that.rewind === false)
{
if(total_length == current_length)
{
// Here I want to pause this function for 3 seconds
setTimeout(that.typingCallback,3000,that);//simply set the 3 second timeout
that.rewind = true;
return;//dont forget to stop the function somewhere here. If not were having two recursive timeout chains... :/
}
//call directly
setTimeout(that.typingCallback,75,that);// the regular timeout

关于javascript - 如何在javascript中暂停递归函数3秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45160542/

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