How to loop a function? - javascript

I am trying to write a code where a sentence is typed word by word on the HTML page and then resets and repeats.
This is the code I am using:
var i = 0;
var txt = 'Welcome';
var speed = 70;
function typeWriter() {
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
var x = 0;
while (x = 0){
typeWriter()
}
Whenever I use this code nothing happens, but when I use window.onload = typeWriter; it works only once. I want to loop, how can I do this?
Example:
var i = 0;
var txt = 'Welcome';
var speed = 70;
function typeWriter() {
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
window.onload = typeWriter;
}

Try this
var i = 0;
var txt = 'Welcome';
var speed = 70;
function typeWriter() {
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}else{
document.getElementById("demo").innerHTML = "";
i = 0;
setTimeout(typeWriter, speed);
}
}
window.onload = typeWriter;
<div id="demo"></div>

you can use setInterval function to repeat the execution, here is a working snippet:
var i = 0;
var txt = 'Welcome';
var speed = 70;
function typeWriter() {
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
var interval = setInterval(function(){
i = 0;
document.getElementById("demo").innerHTML = '';
typeWriter();
}, 1000)
<div id="demo"></div>

I think there is typing mistake. Change the following section of code
while (x = 0){
typeWriter()
}
to
while (x == 0){
typeWriter()
}
because x=0 is not logical operator, it's an assignment operator.

Related

How to Create a Random Text Generator with Countdown Timer in Javascript?

So, I'm trying to create a random text generator in Javascript using Math.floor and Math.random which I combine with countdown timers using Javascript as well. However, the result after the countdown value has been <= 0 does not appear random text that I have made in the function.
In fact, it appears undefined. How's the solution? The script I created is below.
<button id="btn" style="background-color:red;width:30px;height:30px;"></button>
<script>
var timer = 5;
var id;
function create_random_string(string_length){
var random_string = 'X-';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
for (var i, i=0; i < string_length; i++){
random_string += characters.charAt(Math.floor(Math.random() * characters.length))
}
}
function starButton() {
this.style.display = 'none';
id = setInterval(function () {
timer--;
if (timer <= 0) {
clearInterval(id);
document.getElementById("script").innerHTML = create_random_string(5);
} else {
document.getElementById("script").innerHTML = timer + " seconds to get Code";
} }, 1000);
};
var clickbtn = document.getElementById("btn");
clickbtn.onclick = starButton;
</script>
<div id="script"></div>
You were not returning anything from your function. If you don't return function value how it will get it! Check this now.
var timer = 5;
var id;
function create_random_string(string_length){
debugger;
var random_string = 'X-';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
for (var i, i=0; i < string_length; i++){
random_string += characters.charAt(Math.floor(Math.random() * characters.length))
}
return random_string;
}
function starButton() {
this.style.display = 'none';
id = setInterval(function () {
timer--;
if (timer <= 0) {
clearInterval(id);
document.getElementById("script").innerHTML = create_random_string(5);
} else {
document.getElementById("script").innerHTML = timer + " seconds to get Code";
} }, 1000);
};
var clickbtn = document.getElementById("btn");
clickbtn.onclick = starButton;
<button id="btn" style="background-color:red;width:30px;height:30px;"></button>
<div id="script"></div>

I need time delay in every loop iteration. Also let me know alternate of bold <b>

Below is the code for typewriting. After all lines are written, I need them to stay for some seconds and the then disappear for the second loop and so on. Also, let me know what is the alternate of bold <b> for making specific words bold as tags do not work with string. They show < on display during execution. Thanks.
<!DOCTYPE html>
<html>
<body>
<pre id="typing" </pre>
<script>
for (let i=0; i<10; i++) {
task(i);
}
function task(i) {
setTimeout(function() {
// Add tasks to do
var typeString = ['• I \r m Mr.Frits.\n• and I love Pakistan...:)'];
var i = 0;
var count = 0
var selectedText = '';
var text = '';
(function type() {
if (count == typeString.length) {
count = 0;
}
selectedText = typeString[count];
text = selectedText.slice(0, ++i);
document.getElementById('typing').innerHTML = text.fontsize(6);
document.getElementById('typing').style.fontFamily = "monospace";
document.getElementById("typing").style.color = "black";
document.getElementById("typing").style.fontWeight = "normal";
if (text.length === selectedText.length) {
count++;
i = 0;
}
/* SOLUTION : wait two seconds when new line */
if (typeString[0][i-1] == '\n') {
setTimeout(type, 1000);
} else {
setTimeout(type, 100);
}
}());
}, 1000);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<pre id="typing" </pre>
<script>
for (let i=0; i<10; i++) {
task(i);
}
function task(i) {
setTimeout(function() {
// Add tasks to do
var typeString = ['• I \r m Mr.Frits.\n• and I love Pakistan...:)'];
var i = 0;
var count = 0
var selectedText = '';
var text = '';
(function type() {
if (count == typeString.length) {
count = 0;
}
selectedText = typeString[count];
text = selectedText.slice(0, ++i);
document.getElementById('typing').innerHTML = text.fontsize(6);
document.getElementById('typing').style.fontFamily = "monospace";
document.getElementById("typing").style.color = "black";
document.getElementById("typing").style.fontWeight = "normal";
if (text.length === selectedText.length) {
count++;
setTimeout(function(){i = 0;},3000) /*Added this part*/
}
/* SOLUTION : wait two seconds when new line */
if (typeString[0][i-1] == '\n') {
setTimeout(type, 100);
} else {
setTimeout(type, 100);
}
}());
}, 1000);
}
</script>
</body>
</html>
alternate of <b> is <strong>.
you can use css properties to bold your text either. Example:(font-weight:900;)

Stop Looping Text but still run the effect

Example
var text = 'ENTER...';
var chars = text.split('');
var enter = document.getElementById("enter")
var i = 0;
setInterval (function(){
if (i < chars.length){
enter.innerHTML += chars[i++];
}else{
i = 0;
enter.innerHTML = "";
}
}, 200);
I'm trying to have this typing "enter" effect and I am wondering how to make it only go once. So it will type out "ENTER..." and then stop.
Example
var text = 'ENTER...';
var enter = document.getElementById("enter")
var i = 0;
(function nextLetter() {
enter.innerHTML = text.substr(0, ++i);
if (i < text.length) {
setTimeout(nextLetter, 200);
}
})();
edit: you either have to use setTimeout (one time "sleep"), or remember return value of setInterval and destroy that timer by clearInterval after you don't need it/want it running.
If you use interval, you have to stop the it with clearInterval. Stop it inside the interval function, which is declared as a variable, in the if-statement:
var text = 'ENTER...';
var enter = document.getElementById("enter")
var i = 0;
var interval = setInterval(function() {
enter.innerHTML += text[i];
i += 1;
if(i === text.length) {
clearInterval(interval);
}
}, 200);
JSFiddle
var text = 'ENTER...';
var chars = text.split('');
var enter = document.getElementById("enter")
var i = 0;
var interval = setInterval (function(){
if(i == chars.length) {
clearInterval(interval);
return;
}
if (i < chars.length){
enter.innerHTML += chars[i++];
}else{
i = 0;
enter.innerHTML = "";
}
}, 200);
<div id="enter"></div>

Print every loop, not just the final answer

I want the program to print change the innerHTML of th id "resposta" every time a loop runs. But its just changing the value when the loop ends. I want the page to change the content of the div every second.
I have this code:
<script>
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
function escrever(){
for (i = 0; i < 10; i++) {
var resp = "Executando " + i;
document.getElementById("resposta").innerHTML = resp;
sleep(1000);
}
document.getElementById("resposta").innerHTML += "<br> fim";
}
</script>
Best to use setInterval/setTimeout to delay an execution of a function instead of for loops
function escrever(count){
var ele = document.getElementById("resposta");
if(count > 10){
ele.innerHTML += "<br> fim";
return;
}
ele.innerHTML = "Executando " + count;
setTimeout(escrever.bind(null,++count),1000);
}
escrever(1);
<div id="resposta"></div>
Better to use setInterval like bellow
var i = 0;
var interval = setInterval(function(){
var resp = "Executando " + i++;
document.getElementById("resposta").innerHTML = resp;
if(i>=10){
document.getElementById("resposta").innerHTML += "<br> fim";
clearInterval(interval);
}
},1000);
DEMO
<script>
$(document).ready(function(){
var count=0;
interval = setInterval(function() {
if(count<10){
$("#resposta").html('test'+count);
} else {
clearInterval(interval);
}
count ++;
},1000);
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="resposta"></div>
You can use setTimeout():
var timeout;
function sleepME(i){
if(i <= 10){
timeout = setTimeout((function(){
var resp = "Executando " + i;
document.getElementById("resposta").innerHTML = resp;
sleepME(++i);
}), 1000);
} else {
document.getElementById("resposta").innerHTML += "<br> fim";
clearTimeout(timeout);
}
}
sleepME(1);
<div id="resposta"></div>

Javascript falling letters: Every other letter different direction

I'm having a hard time finding a way to insert falling letters into my code. My task is to have a text string and have all the even-placed letters fall from the top and the odd-placed letters fly from the bottom and come together to form the string in the center.
So for instance, I have: <span class="uName">John Doe</span>
I would like the letters: O, N, D, E to fall from the top.
Likewise: J H _ O to fly up from the bottom. (keeping their respective horizontal positions).
Here's what I have so far, however I'm fairly inexperienced with JavaScript/JQuery and I can't get it to run.
vertical = new Array(80);
var textPos = 0;
for(var i = 0; i < 80; ++i) {
vertical[i] = textPos;
textPos += 5;
}
function poz(){
document.getElementsByClassName("tops").style.top = '0px';
document.getElementsByClassName("bottoms").style.bottom = '0px';
animate();
}
function animate(){
for(var j = 0; j < 80; ++j) {
document.getElementsByClassName("tops").style.top = vertical[j] + "px";
document.getElementsByClassName("bottoms").style.bottom = vertical[j] + "px";
}
}
$('.uName').each(function(){
var letters = $(this).text().split('');
$(this).text('');
for(var i = 0; i < letters.length; i++){
if(i % 2 == 0){
$(this).append('<span class="tops">' + letters[i] + '</span>');
}
else{
$(this).append('<span class="bottoms">' + letters[i] + '</span>');
}
}
poz();
});
Thanks so much in advanced!
P.S. If this task can be achieved with just CSS3, I would much prefer that option but I'm not sure if it's possible.
//css
.bottoms{
margin-top:200px!important;
}
//Script
vertical = new Array(80);
var textPos = 0;
for(var i = 0; i < 80; ++i) {
vertical[i] = textPos;
textPos += 5;
}
function poz(){
// $(".tops").css('top','0px');
// $(".bottoms").css('bottom','0px');
//document.getElementsByClasjqsName("bottoms").style.bottom = '0px';
animate();
}
function animate(){
for(var j = 0; j < 80; ++j) {
//alert(vertical[j]);
//$(".tops").css('top',vertical[j]+'px');
//$(".bottoms").css('bottom',vertical[j]+'0');
if(vertical[j]<101){
$(".tops").animate({top:vertical[j]+'px'},500);
$(".bottoms").animate({bottom:vertical[j]+'px'},500);
$(".tops").css('position','relative');
$(".bottoms").css('position','relative');
$(".tops").css('float','left');
$(".bottoms").css('float','left');
}
// document.getElementsByClassName("tops").style.top = vertical[j] + "px";
// document.getElementsByClassName("bottoms").style.bottom = vertical[j] + "px";
}
}
$('.uName').each(function(){
var letters = $(this).text().split('');
$(this).text('');
for(var i = 0; i < letters.length; i++){
if(i % 2 == 0){
$(this).append('<span class="tops">' + letters[i] + '</span>');
}
else{
$(this).append('<span class="bottoms">' + letters[i] + '</span>');
}
}
poz();
});
//NEW Fiddle link http://jsfiddle.net/PP44C/7/
Now everything is fine as you want . check it

Categories