Hello World
Hello World

Reputation: 371

How to reset and repeat this function triggered by a button by pressing that button again?

I have a function that chooses a random string from an array and types it in a paragraph. I trigger this function by pressing a button.

var myArray = ['something', 'something else', 'another thing',]; 
var rand = myArray[Math.floor(Math.random() * myArray.length)];
var i = 0;      
var speed = 55; 
function typeWriter() {
  if (i < rand.length) {
    document.getElementById("question").innerHTML += rand.charAt(i);
    i++;
    setTimeout(typeWriter, speed);
  }
}
<button class="button next" id = "next" onclick="typeWriter()"> Next</button>

<p id="question"></p>

Pressing the "next" button triggers the typeWriter function, which chooses a random string from myArray and begins to type it in the paragraph "question". What I want to happen is, upon pressing "next" again (either while the typing is going on or after the typing is done), the text that has been typed already is deleted and the typeWriter triggers again, choosing another string and typing it in paragraph "question".

Upvotes: 0

Views: 181

Answers (2)

ZorgoZ
ZorgoZ

Reputation: 3569

You want something like this?

var myArray = ['something', 'something else', 'another thing',]; 
var speed = 100;

var target = document.getElementById("question");
var char;
var timer;
var sentence;

function type(){
  if(char < sentence.length) {
    target.innerHTML += sentence.charAt(char++);
  } else {
    clearInterval(timer);
  } 
}

function reset() {
  clearInterval(timer);
  sentence = myArray[Math.floor(Math.random() * myArray.length)];
  char = 0;
  target.innerHTML = '';
}

function typeWriter() {
  reset();  
  timer = setInterval(type, speed);
}
<button class="button next" id = "next" onclick="typeWriter()"> Next</button>

<p id="question"></p>

The setTimeout you have used implies that each time a character is "pressed", a new timer is started. My approach is to use an interval timer, which is simply writing the next character until the sentence ends or the typewriter is reset. In these two cases, the timer is cleared.

Upvotes: 1

Vishal modi
Vishal modi

Reputation: 1720

if you are fetching random string then you need to write that code inside your function. please try below solution.

<button class="button next" 
   id = "next"
   onclick="typeWriter()">
  Next
</button>

<p id="question"></p>

<script>

var myArray = ['a', 'b', 'c',]; 

var i = 0;      
var speed = 55; 
   
 function typeWriter() {
   
  var rand = myArray[Math.floor(Math.random() * myArray.length)];
  
  if (i < rand.length) {
    document.getElementById("question").innerHTML = rand.charAt(i);
    i++;
    setTimeout(typeWriter, speed);
  }
  else
  {
   i--;
  }
}
</script>

Upvotes: 0

Related Questions