0

This is my HTML file:-

<!DOCTYPE html>
<html>
<head>
  <title>My Page</title>
  <script type="text/javascript">
    var stringArray = new Array();
    stringArray[0] = "Hi";
    stringArray[1] = "how";
    stringArray[2] = "are";
    stringArray[3] = "you?";
    var i = 0;
    while(i<stringArray.length)
    {
        setTimeout(print,3000,i);
        i++;
    }

    function print(k)
    {
        console.log(stringArray[k]);
    }

   </script>
</head>
</html>

Here I am trying to display each of the string in array stringArray at an interval of 3 sec. But when the page loads there is a pause of 3 sec only at the beginning and then all of the 4 string in my array are displayed together. It seems that setTimeout() takes effect only for the first time. Can anyone suggest what is happening here and also what changes do I need to make to display each of the individual strings at 3 sec interval.

Parag Kadam
  • 3,620
  • 5
  • 25
  • 51

0 Answers0