【问题标题】:How to make this function do this in an interval如何使此功能在一段时间内执行此操作
【发布时间】:2017-01-05 23:05:04
【问题描述】:

我正在尝试获取第一个功能,以重复运行。就像它在第二个功能中一样。我应该去哪里看?

     (function printLetterByLetter() {
    var i = 0;
    var destination = "comment";
    var RandomComment = [
    "Did you choose that outfit?"
    , "I like trains."];
    var message = RandomComment[Math.floor(Math.random() * RandomComment.length)];
    var typewriter = function () {
        document.getElementById(destination).innerHTML += message.charAt(i);
        i++;
        if (i > message.length) {
            clearInterval(typespeed);
        }
    }
    var speed = 60;
    var typespeed = setInterval(typewriter, speed)
}());



(function printLetterByLetter() {
     var destination = "comment";
     var frequency = 1000;
     var RandomComment = [
        "Did you choose that outfit?"
        , "I like trains."];
     var RandomCommentTimer = setInterval(function () {
        var message = RandomComment[Math.floor(Math.random() * RandomComment.length)];

    }, frequency)
}());

所以我要做的是制作一个函数/模块,以设定的速度(第一个函数)键入随机评论。并且在设定的时间后评论会消失,并且会输入新的评论(第二个功能)。就像第二个功能一样,这将继续。 到目前为止,我自己还没有成功,所以我想:让我们看看是否有人可以在 stackoverflow 上帮助我。

如果有人可以提供关于在哪里看的提示,那也是非常受欢迎的。

标签: javascript arrays module innerhtml charat


【解决方案1】:

您可以在函数外部设置和更改函数参数,然后在内部访问它们。需要注意的是,设置它们时不能将var 放在前面。不将 var 放在前面使其可以在当前范围之外访问。

destination = "comment";
frequency = 6000;
(function printLetterByLetter() {
//now you have access to destination and frequency as they are defined before the function is called
var RandomComment = [
"Did you choose that outfit?"
, "I like trains."];
var RandomCommentTimer = setInterval(function () {
    var message = RandomComment[Math.floor(Math.random() * RandomComment.length)];
    document.getElementById(destination).innerHTML = message;
}, frequency)
}());

【讨论】:

  • 好的,谢谢,这看起来更好。但这不是我卡住的部分。
猜你喜欢
  • 1970-01-01
  • 2013-09-04
  • 1970-01-01
  • 1970-01-01
  • 2021-04-01
  • 2012-12-25
  • 2021-10-27
  • 2010-10-03
  • 2011-07-21
相关资源
最近更新 更多