How to make this function do this in an interval

73 views Asked by At

I'm trying to get the first function, to run repeatedly. Like it does in the second function. Where should I take a look?

     (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)
}());

So what i'm trying to do is to make one function/module that types out a random comment at a set speed(first function). And after a set time the comment will disappear and a new comment will be typed out(second function). And like the second function this will go on. So far I haven't made it work myself so I thought: let's see if anyone can help me on stackoverflow.

If anyone can give a tip on where to take a look, that is also most welcome.

1

There are 1 answers

1
Ray On

You could set and alter the function parameters outside of the function then access them inside. Caveat is that you can't put var in front when setting them. Not putting var in front makes it accessible outside of the current scope.

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)
}());