使用回调函数 Javascript 在屏幕上打印数组元素 Delay/Repeating

Printing on screen array elements with Delay/Repeating them by using a callback function Javascript

我正在尝试打印给定的数组单元格,每次打印之间的每个元素都有 2 秒的延迟 通过使用 callback 函数,但我无法使其工作。 相反,它会在 2 秒后将它们全部打印出来

代码如下:

var words = ["horse","pig","fish","lion"]
var time

function display(callback){
    time = setTimeout(typing, 2000);
}

function typing(){
    for (var i=0; i<words.length; i++)
        document.write(words[i])
}
display(typing);

如果可能的话,我也可以使用此代码的一些帮助。如果第一个变量(在本例中为 a)是一个数字,而第二个变量(在本例中为 b)是一个字符串,它应该打印字符串的次数与变量 a 的次数一样多。 这个根本不起作用:/

代码如下:

function display(callback) {
   time = setTimeout(typing, 1000)
}
function typing(a,b) {
   var aInput = prompt("Please enter a input");
   aInput = a
   var bInput = prompt("Please enter b input");
   bInput = b
     if (a === int)
       for (i=0; i<a.length; i++)
          alert(b)
   else 
      alert("Not valid Input")
    }

display(typing);

提前非常感谢这个社区为初学者提供的巨大帮助:)

从表面上看,你应该做这部分:

var aInput = prompt("Please enter a input");
aInput = a
var bInput = prompt("Please enter b input");
bInput = b

之前:

time = setTimeout(typing, 1000)

然后将您的 a 和 b 参数发送至:

typing(a,b)

如果你这样做,它应该会起作用。

回答你的第一个问题。所有的单词都在 2 秒后打印出来,因为 for 循环不会在每个循环中等待 setTimeout 的执行完成,因此它几乎立即运行所有 setTimeouts 并且每个循环都在等待2秒,显然是同时完成。你可以这样改。

var words = ["horse","pig","fish","lion"]

function display() {
  let counter = 0;
  const interval = setInterval(() => {
    document.write(words[counter++]);
    if (counter === words.length) {
      clearInterval(interval);
    }
  }, 2000);
}

display();

关于第二个问题。这可以用类似的方式解决。

function display(a, b) {

  // if a and b were passed to the function use those
  // otherwise ask for them by prompting the user
  let aInput = a || prompt('Please enter a input');
  let bInput = b || prompt('Please enter b input');

  // check if a is valid integer (could also use Math.floor if floats are valid in your case as well)
  if (!isNaN(parseInt(a))) {
    let counter = 0;
    const interval = setInterval(() => {
      alert(b);
      counter++;
      if (counter >= parseInt(a)) {
        clearInterval(interval);
      }
    }, 2000);
  } else {
    alert('Not a valid input');
  }
}

display(4, 'a');

第二个代码有一些问题:

  1. 您正在通过 prompt 进行输入,因此您不需要将任何参数传递给 typing
  2. 由于上述原因,a和b未定义。所以,aInput = abInput = b 没有意义。相反,将 aInput 和 bInput 的值分别存储在 a 和 b 中。
  3. if (a === int) 是错误的语法。 JavaScript中没有int这样的东西。如果您想检查 a 是否为数字,请使用 isNaN(a).
  4. if-statement 中的 for loop 必须包含在 {} 中,因为它有多行。

这应该可以正常工作:

function display(callback) {
   time = setTimeout(typing, 1000)
}

function typing() {
   var aInput = prompt("Please enter a input");
   var a = Number(aInput); 
   var bInput = prompt("Please enter b input");
   var b = bInput;
     if (!isNaN(a)){
       for (var i=0; i<a; i++){
          alert(b);
        }
    }
   else {
      alert("Not valid Input")
    }
}

display(typing);