3

I am trying a little bit of coding and I would like for the 30 character strings to appear in the 1 second intervals one after another when the code is started. I tried setInterval & setTimeout and I couldn't get it to work. If someone could please help that would be much appreciated.

count = 0
while (count < 200) {
    console.log(create_random_string(30))

function create_random_string(string_length){
    var random_string = '';
    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'
    for(var i, i = 0; i < characters.length; i++){
        random_string += characters.charAt(Math.floor(Math.random() * characters.length))
    }
    return  "|BTC| " + random_string +  "  | " + " PRIVATNI KLJUČ NIJE ISPRAVAN" + "  | " + " STANJE: 0.00"
}
count = count + 1
}
Max Alexander Hanna
  • 3,388
  • 1
  • 25
  • 35
miki261
  • 31
  • 3
  • The Java script is not equal to javascript. – user17517503 May 02 '22 at 20:37
  • Declaring a `var` inside a function means the variable is created and destroyed each time the function runs. Using setInterval means a function provided by you runs every X milliseconds. The string variable you want to build has to be declared outside that function or everything starts over again each time. –  May 02 '22 at 20:37
  • answered the question, welcome to StackOverflow, if the answer is good, don't forget to designate it as the "accepted answer" and upvote it :) thanks – Max Alexander Hanna May 02 '22 at 20:45

1 Answers1

0
setInterval(code, time); 

this function will allow you to wait X miliseconds before running the code defined.

here, the correct code, and i fixed your formatting a bit.

let count = 0;
while (count < 200) {
    setTimeout(
        function() { console.log(create_random_string(30)); }
        , 500);
    count++;
}

function create_random_string(string_length){
    var random_string = '';
    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'
    for(var i, i = 0; i < characters.length; i++){
        random_string += characters.charAt(Math.floor(Math.random() * characters.length))
    }
    return  "|BTC| " + random_string +  "  | " + " PRIVATNI KLJUČ NIJE ISPRAVAN" + "  | " + " STANJE: 0.00"
}

by the way, you probably wanted to replace characters.length inside your for loop for : string_length to use the fuction's parameter (which you never actually used)

Max Alexander Hanna
  • 3,388
  • 1
  • 25
  • 35
  • I get an error when I run your code, https://prnt.sc/YBeHZj4sovLy, no idea what to do, it only displays one 30 character string and then it gives an error. I want it to display 200 30 character strings in the intervals of 1 second between each – miki261 May 03 '22 at 07:48
  • "callback must be a function" means you needed to surround your console.log(create_random_string(30)) in a function. I updated the code for you. – Max Alexander Hanna May 05 '22 at 21:54