Appending to empty element does not work - javascript

I want to display the characters of a string, stored in an array, one by one.
When I call threadsleep(a) using the following code: http://jsfiddle.net/thefiddler99/re3qpuoo/, it appears all at once.
The problem lies somewhere here I presume
for (var i = 0; i < str.length; i++) {
$('#hello').append(str[i])
alert("foo")
sleep(500)
};
The alert shows that everything is working properly except that the interval between each is not present.
I cannot figure out why.
Note: Sleep is a function I have defined that works for the set amount of time

JavaScript is single threaded. It is too busy running round and round your while loop to perform a repaint of the page.
Don't try to write a sleep function. The language isn't suited to it and it just chomps CPU. Rewrite your code to use setInterval or setTimeout instead.
var i = 0;
next();
function next() {
$('#hello').append(str[i]);
i++;
if (i < str.length) {
setTimeout(next, 500);
}
}

Just try with setTimeOut recursion call.
Demo
<script>
var text="This string will be display one by one.";
var delay=500;
var elem = $("#oneByOne");
var addTextByDelay = function(text,elem,delay){
if(!delay){
delay = 500;
}
if(text.length >0){
//append first character
elem.append(text[0]);
setTimeout(
function(){
//Slice text by 1 character and call function again
addTextByDelay(text.slice(1),elem,delay);
},delay
);
}
}
addTextByDelay(text,elem,delay);
</script>

Related

Creating a for loop that loops over and over =

So I have a weird problem (as I can do this using dummy code, but cannot make it work in my actual code) -
The concept is simple - I need a for loop that upon hitting its max "I" number reverts "I" to 0 again and creates a loop over and over -
DUMMY CODE:
for(i=0;i<10;i++){
console.log(i);
if(i === 10){
i = 0
}
}
Now for the longer code (sorry)
function reviewF(){
// add ID to each of the objects
reviews.forEach((e, i)=>{
e.id = i
})
// get the elements to be populated on page
var name = document.querySelector('p.name');
var date = document.querySelector('p.date');
var rating = document.querySelector('.rating_stars');
var review = document.querySelector('p.review_content_text');
// reverse the array - so the newest reviews are shown first (this is due to how the reviews where downloaded)
var reviewBack = reviews.slice(0).reverse();
// start the loop - go over each array - take its details and apply it to the elements
/**
* THIS IS WHAT I WOULD LIKE TO LOOP OVER FOREVER
*
* **/
for (let i = 0; i < reviewBack.length; i++) {
(function(index) {
setTimeout(function() {
// document.getElementById('reviews').classList.remove('slideOut')
name.classList.remove('slideOut')
date.classList.remove('slideOut')
rating.classList.remove('slideOut')
review.classList.remove('slideOut')
name.classList.add('slideIn')
date.classList.add('slideIn')
rating.classList.add('slideIn')
review.classList.add('slideIn')
name.innerHTML = reviewBack[i].aditional_info_name;
date.innerHTML = reviewBack[i].Date;
rating.innerHTML = '';
review.innerHTML = reviewBack[i].aditional_info_short_testimonial;
if(reviewBack[i].aditional_info_short_testimonial === 'none'){
reviewBack.innerHTML='';
}
var numberOfStars = reviewBack[i].aditional_info_rating;
for(i=0;i<numberOfStars;i++){
var star = document.createElement('p');
star.className="stars";
rating.appendChild(star);
}
setTimeout(function(){
// document.getElementById('reviews').classList.add('slideOut')
name.classList.add('slideOut')
date.classList.add('slideOut')
rating.classList.add('slideOut')
review.classList.add('slideOut')
},9600)
}, i * 10000)
})(i);
// should create a infinite loop
}
console.log('Loop A')
}
// both functions are running as they should but the time out function for the delay of the transition is not?
reviewF();
EDITS >>>>>>>>
Ok so I have found a hack and slash way to fix the issue - but its not dry code and not good code but it works.....
this might make the desiered effect easier to understand
reviewF(); // <<< this is the init function
// this init2 function for the reviews waits until the reviews have run then
// calls it again
setTimeout(function(){
reviewF();
}, reviews.length*1000)
// this version of the innit doubles the number of reviews and calls it after that amount of time
setTimeout(function(){
reviewF();
}, (reviews.length*2)*1000)
From trying a bunch of different methods to solve this issue something I noticed was when I placed a console.log('Finished') at the end of the function and called it twice in a row (trying to stack the functions running..... yes I know a horrid and blunt way to try and solve the issue but I had gotten to that point) - it called by console.log's while the function was still running (i.e. the set time out section had not finished) - could this have something to do with it.
My apologies for the rough code.
Any help here would be really great as my own attempts to solve this have fallen short and I believe I might have missed something in how the code runs?
Warm regards,
W
Why not simply nest this for loop inside a do/while?
var looping = True
do {
for(i=0;i<10;i++){
console.log(i);
}
if (someEndCondition) {
looping = False;
}
}
while (looping);
I would think that resetting your loop would be as simple as setting "i = 0" like in the dummy code. So try putting the following into your code at the end of the for loop:
if(i === 10){
i = 0;
}

Set a delay between each element in an array using a for loop

I'm trying to change the opacity of each element in an array but with a slight delay between each element. I've tried a bunch of variations of the simplified code snippet below but each time either they all change at once with a delay or nothing changes. Whats the correct syntax for this code?
for (let i = 0; i < testArray.length; i++) {
setTimeout(function() {testArray[i].style.opacity = ".5"}, 500);
}
Since you're using let asynchronicity is not the issue here rather it's just timing.You just need to change
setTimeout(function() {testArray[i].style.opacity = ".5"}, 500);
To
setTimeout(function() {testArray[i].style.opacity = ".5"}, 500*(i+1));
This would set timer for items in increasing amounts of 500 ms like 500,1000,1500 and so on
Try using setInterval in case it didn't work with setTimeout like the following :
var counter = 0;
var arrayLength =testArray.length;
var refOfSetInterval;
function changeOpacity(){
if(counter < arrayLength){
testArray[counter].style.opacity = ".5";
counter++;
}
else{
clearInterval(refOfSetInterval);
}
}
refOfSetInterval = setInterval(changeOpacity,1000);
you can use $('').slideUp(2000); method to delay between your two element i used this several times.its works fine

While loop and setInterval()

I am trying to mix the initial string and randomly compare the string's elements with the right elements on the right indexes, and if true push them into a set, to reconstruct the initial string. Doing this I met the problem that while loop does nothing just crushng the browser. Help me out with this.
function checker() {
var text = document.getElementById("inp").value;
var a = [];
var i = 0;
while (a.length < text.length) {
var int = setInterval((function() {
var rnd = Math.floor(Math.random() * text.length);
if (text[rnd] === text[i]) {
a.push(text[rnd]);
clearInterval(int);
i++;
}
}), 100)
}
}
P.S. I need the setInterval() function because I need the process to happen in exactly the same periods of time.
So, you stumbled into the pitfall most people hit at some point when they get in touch with asynchronous programming.
You cannot "wait" for an timeout/interval to finish - trying to do so would not work or block the whole page/browser. Any code that should run after the delay needs to be called from the callback you passed to setInterval when it's "done".
In my answer its doing exactly what you want - creating exactly the same string by randomly mixing the initial, and also using setInterval. You didn't write where you want the result, so you have it written in the console and also in another input field with id output_string.
HTML:
<input id="input_string" value="some_text" />
<input id="output_string" value="" readonly="readonly" />
JavaScript:
function checker() {
var text = document.getElementById("input_string").value;
var result = '';
// split your input string to array
text = text.split('');
var int = setInterval((function() {
var rnd = Math.floor(Math.random() * text.length);
// add random character from input string (array) to the result
result += text[rnd];
// remove used element from the input array
text.splice(rnd, 1);
// if all characters were used
if (text.length === 0) {
clearInterval(int);
console.log(result);
document.getElementById("output_string").value = result;
}
}), 100);
}
checker();
DEMO
Honestly, I have no idea what you are trying to do here, but you seem to have lost track of how your code is operating exactly.
All your while loop does, is creating the interval, which is ran asynchronous from the loop itself.
In other words, the only way your while condition equates to false, is after multiple 100ms intervals have elapsed. 100 miliseconds is an eternity when comparing it to the speed of 1 loop iteration. We're looking at 1000s of iterations before your first setInterval even triggers, not something a browser can keep up with, let alone wait several of these intervals before you change a.length.
Try more like this:
function checker() {
var text = document.getElementById("inp").value;
var a = [];
var i = 0;
// start to do a check every 100ms.
var interv = setInterval(function() {
var rnd = Math.floor(Math.random() * text.length);
if (text[rnd] === text[i]) {
a.push(text[rnd]);
i++;
}
// at the end of each call, see if a is long enough yet
if(a.length > text.length){
clearInterval(interv); // if so, stop this interval from running
alert(a); // and do whatever you need to in the UI.
}
}, 100);
}
}

Simple Looping In Java Script

I made a simple loop and would like to know how to carry this out.
The variable's name is Math, and it is equal to 4. I am trying to write a simple looping statement that says: "While Math is not equal to 4, await your number"
Here is the code I have so far:
var math = 2+2;
var loop = function(){
for(var i=0; i < 5; i++)
{
while (math[i] != 4)
{
console.log ("Await until you reach 4");
}
}
};
loop();
The following code will do what you presumably want:
var math = 2+2;
var loop = function(){
var i = 0;
while (i !== math) {
i++;
console.log ("Await until you reach 4");
}
}
loop();
Note that technically, the for loop in javascript (as well as in many other languages) actually is not that much different from a while loop, as the code for initialization, increment and termination is rather unrestricted. You are not even forced to have an iteration variable in you for loop.
The difference is in someone else's ease of understanding of your code (or your's after you haven't looked into you code for some time). for suggests a counted iteration of a list, while some operations to be performed while (sic!) a condition is fulfilled without which the operation make no sense or produce the wrong result.
This concept will create an endless loop, that waits for something to edit the variable.
As javascript occupies the thread its running in, all events will be waiting for this endless loop to end.
If it's part of the main GUI thread, (normal javascript) this means that your page will hang. Only use this method for webworkers, or extensions.
Instead redesign as eventhandlers, instead of a main loop
edit: having read your comments, and found out what you are trying to do:
var math = 2+2;
for(var i = 0; i < 5; i++){
if(i != math){
console.log ("Await until you reach 4");
continue
}
alert("yay")
}
or with a while loop
var math = 2+2;
var i = 0;
while(math != i){
if(i != math){
console.log ("Await until you reach 4");
}
i++;
}
alert("yay")
Maybe this is what you are trying to do:
var math = 2+2;
var loop = function(){
for(var i=0; i < 5; i++){
if(i != math){
console.log ("Await until you reach 4");
}else{
console.log("You have reached 4");
}
};
loop();
Using while
var math = 2+2;
var loop = function(){
var i=0;
while(i != math){
console.log ("Await until you reach 4");
i++;
}
};
loop();
var loop = function(math){
var i = 0;
while(i!==math){
console.log ("Await until you reach 4");
i++;
}
}
loop(2+2);

Run a for loop. Increment the value; exit and begin loop again with new value

I want to run a loop. I want it to excecute it 16 times like,
for (var i = 0; i <= 15; i++) {
alert(i);
}
I want this loop to run on clicking a button. But the loop should only return the first value of i and then exit. Like this,
for (var i = 0; i <= 15; i++) {
alert(i);
exit();
}
What I am confused with is, whenever I click the button I want this loop to run-only once-but with the value being incremented by one. The whole idea is to alert the i value on each click of the button but incremented by one each time. I think even my use of for loop also is not making any sense. Or is my whole logic wrong. I think I am doing something more complex where something simple like using counter will accomplish the same. Any help appreciated.
var myVal = 0;
function incrementValue(){
myVal++;
alert(myVal);
}
Just increment a variable every time you call the function.
If I am getting it right, it should be somewhat like this,
var btn_init = 0;
//on click
$(function(){
$('#your_button_id').on('click',function(){
btn_init++; //increment
alert(btn_init);
}
});
<div class="button1">click</div>
<div class="valuecontainer"></div>
<script>
var i=0;
var x=15;
$('.button1').click(function(){
if(i<x){
i++;
$('.valuecontainer').html(i);
}
else
{
alert("rechaed limit");
}
});
</script>
I guess you will find your answer here:
Count function call in JS
This is the shortest code found there though i donot completely understand this (somebody plz explain):
function myFunction() {
this.num = (this.num || 0) + 1;
if(this.num <= 15)
alert(this.num);
}

Categories