Print every loop, not just the final answer - javascript

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>

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>

How to loop a function?

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.

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>

setInterval into Infinity loops

Her is my new code with setinternal of 4 images. However, I am trying to have an infinite loops of the same images. Can you help me to understands how to create a setInterval loop.
<script type="text/javascript" >
var OpenWindow = window.open("","","top=100, left=400,resizable=yes,height=550,width=550,menubar=yes,location=yes,resizable=yes,scrollbars=yes");
var imgURLS = ['Oculus.jpg', 'future-vr.jpg', 'morpheus.jpg', 'samsungvr.jpg'];
var imgIndex = 0;
var timer = setInterval(function() {
for (var imgIndex = 0; j < imgURLS.length; j++)
{
for (var imgIndex = 0; i < imgURLS.length; i++)
{
clearInterval(timer);
} else {
OpenWindow.document.write("<div class='css-slideshow'>");
OpenWindow.document.write("<figure>");
OpenWindow.document.write('<img src ="' + imgURLS[imgIndex++] + '">');
OpenWindow.document.write("</figure>");
OpenWindow.document.write("</div>");
}
}, 3000);
</script>
I just figure out how to make longer loops. However, my images are showing broke?
<script type="text/javascript" >
var OpenWindow = window.open("","","top=100, left=400,resizable=yes,height=550,width=550,menubar=yes,location=yes,resizable=yes,scrollbars=yes");
var imgURLS = ['Oculus.jpg', 'future-vr.jpg', 'morpheus.jpg', 'samsungvr.jpg'];
var imgIndex = 0;
var i = setInterval(function() {
imgIndex++;
if(imgIndex === 20) {
clearInterval(i);
} else {
OpenWindow.document.write("<div class='images-1'>");
OpenWindow.document.write('<img src ="' + imgURLS.length + '">');
OpenWindow.document.write("</div>");
}
}, 3000);
</script>
I figure out why the image were broke. it was missing this imgURLS[imgIndex]
new code is:
OpenWindow.document.write('<img src ="' + imgURLS[imgIndex] + '">');
OpenWindow.document.write('<img src ="' + imgURLS.length + '">');
Here's a simple way with setTimeout.
1) Add an id to your containing div and target it.
var image = document.querySelector('#css-slideshow img');
2) Use setTimeout to repeatedly call the same loop function with increments of count. If count equals the length of the images array, set it to zero.
function carousel() {
var timer, count = 0;
var loop = function loop(count) {
if (count === imgURLS.length) count = 0;
image.src = imgURLS[count];
timer = setTimeout(loop, 2000, ++count);
}
loop(count);
}
carousel();
DEMO

How can I have a live timer that updates every seconds within a 3 second loop?

I'm using some code like this
window.setInterval(function(){
//Code goes here
}, 3000);
for a 3 seconds loop, and I want to have a timer counting up within that that updates every seconds instead of every 3 seconds, is that possible?
I tried putting this in the loop:
var stmints = 0;
var stseconds = 0;
var stzecsec = 0;
function toAutoStop() {
alert('Your life goes on');
}
var zecsec = 0;
var seconds = 0;
var mints = 0;
var startchron = 0;
function chronometer() {
if(startchron == 1) {
zecsec += 1; // set tenths of a second
if(zecsec > 9) {
zecsec = 0;
seconds += 1;
}
if(seconds > 59) {
seconds = 0;
mints += 1;
}
document.getElementById('showtm').innerHTML = mints+ ' : '+ seconds+ '<sub>'+ zecsec+ '</sub>';
if(zecsec == stzecsec && seconds == stseconds && mints == stmints) toAutoStop();
else setTimeout("chronometer()", 100);
}
}
function startChr() { startchron = 1; chronometer(); } // starts the chronometer
function stopChr() { startchron = 0; } // stops the chronometer
function resetChr() {
zecsec = 0; seconds = 0; mints = 0; startchron = 0;
document.getElementById('showtm').innerHTML = mints+ ' : '+ seconds+ '<sub>'+ zecsec+ '</sub>';
}
startChr();
You may want to make your period 1s then:
var UPDATE_PERIOD = 1;
var ACTION_PERIOD = 3 * UPDATE_PERIOD;
var passed = 0;
setInterval(function() {
passed += UPDATE_PERIOD;
updateTimer();
if(passed % ACTION_PERIOD === 0) {
doStuff();
}
}, UPDATE_PERIOD * 1000);
function updateTimer() {
document.getElementById("timer").textContent = "" + passed + "s";
}
function doStuff() {
// do your stuff here
}
Very simple example: http://jsbin.com/aSAQiYud/1/edit
http://jsfiddle.net/459Lt/
this is actually very easy. I used jquery but that's for just selecting elements. Nothing truly that controls logic.
w.clone().appendTo('body'); is where you would like to put function that needs to be called... like dowork().....
var t=0, w=$('.w'),txt=$('.text');
setInterval(f,1000);
function f(){
txt.text(t+1);
if(t==2) w.clone().appendTo('body');
t=++t%3;
}

Categories