First, my HTML:
<p id="p"></p>
<input id="input" />
<button onclick="fill()">Fill</button>
Then my Javascript:
function fill() {
var x = document.getElementById('input').value;
var y = x.split('');
for (var i = 0; i < y.length; i++) {
if (i == 0) {
setTimeout(function() {
document.getElementById('p').innerHTML = y[i];
},(i * 50));
}
setTimeout(function() {
document.getElementById('p').innerHTML += y[i];
},(i * 50));
}
}
What it does is take text from a textfield, cut each character including spaces into an array, then loop through the array, displaying each character at 50ms intervals. The effect is supposed to look like it is typing itself out.
The effect works fine, but the values of the array don't seem to be. If I were to type "abc123" then I would expect that to come right back out, but instead I get:
undefinedundefinedundefinedundefinedundefinedundefined
Using console.log(), when I check the array it looks fine, when I check the typeof of the individual array values I get string, but when I check the typeof for the array, I get object. Maybe this is what's wrecking it...
I have tried use toString() on the y[i] which just spits out "[object Window]", I have tried defining the array like this var y = new Array; and then doing the split(), nothing works. I am at a complete loss. Really would love some help here. Thanks!
I believe there must be closure problem. Try this js code. I wrapped everything inside loop in a IIFE function. I think it is well explained here Please explain the use of JavaScript closures in loops
<script>
function fill() {
var x = document.getElementById('input').value;
var y = x.split('');
for (var i = 0; i < y.length; i++) {
(function(i){
if (i == 0) {
setTimeout(function() {
document.getElementById('p').innerHTML = y[i];
},(i * 50));
}
setTimeout(function() {
document.getElementById('p').innerHTML += y[i];
},(i * 50));
})(i);
}
}
</script>
By calling setTimeout you're scheduling something to happen in the future. By the time the function you're delaying with setTimeout is executed, the loop has executed all the way through and i is now equal to y.length. So if you input test when the function executes it tries to add y[4] as a letter which is undefined. To fix it, you can do something like this:
function fill() {
var x = document.getElementById('input').value;
var y = x.split('');
console.log(y);
for (var i = 0; i < y.length; i++) {
timeOutAdd(y[i], i*50)
}
}
function timeOutAdd(c, delay){
setTimeout(function() {
document.getElementById('p').innerHTML += c;
}, delay);
}
<p id="p"></p>
<input id="input" />
<button onclick="fill()">Fill</button>
By adding the timeOutAdd function which is called immediately instead of delayed we can hang on to the values of the parameters until the setTimeout function runs.
Note: I also removed the second call to setTimeout, it wasn't necessary and caused a bug where the first character of the string was output twice.
This solves the closure problem, plus it simplifies the logic for outputting the data. No need for splitting the string into an array:
function fill() {
var x = document.getElementById('input').value,
p = document.getElementById('p');
for(var i = 0; i < x.length; i++) {
(function(i) {
setTimeout(
function() {
p.innerHTML= x.substr(0, i+1);
},
i*50
)
})(i);
}
}
<p id="p"></p>
<input id="input" value="abcde" />
<button onclick="fill()">Fill</button>
Related
I’m trying to use an increment loop but I want it to increment at the end of the loop. Sadly, whenever I simply put the i++ at the end of the loop it doesn’t behave like I’d expect or want it to. Anyone mind showing me the proper way of doing it?
The referred increment loop:
for (i = 1; i < 15; i++) {
// do somthing here
}
Here is the loop I’m working with:
for (i = 1; i < 15; i++) {
for (x = 1; x < 15; x++) {
var take = document.getElementById("row" + i + "sm" + x);
Tesseract.recognize(take)
.then(function(result) {
console.log(result.text);
// rows[i][x] = result.text;
})
}
}
What I’d like it to do:
for (i = 1; i < 15) {
for (x = 1; x < 15) {
var take = document.getElementById("row" + i + "sm" + x);
Tesseract.recognize(take)
.then(function(result) {
console.log(result.text);
//rows[i][x] = result.text;
x += 1;
})
i += 1;
}
}
I am using the for loop because I need to iterate over something one by one. How do I properly increment i at the end of the loop?
Here is a video explaining my problem with context and explanation why it is not an ASYNC problem. Sorry if it is hard to follow, ill update it with audio soon so I can explain it propperly.
https://drive.google.com/file/d/1n1ZwNJif5Lb5zfLb2GPpBemObwpOqNf7/view
The problem is that the second one doesnt wait until first one is complete.
You can try with recursion inside then. There maybe some mistake with i,x but you get the point.
You execute first with i=1 and x=1, after the operation is done (then) you call the next until all elements are executed.
function execItem(i, x) {
var take = document.getElementById("row" + i + "sm" + x);
Tesseract.recognize(take)
.then(function(result){
rows[i][x] = result.text;
if (i < 15 && x < 15) {
if (i > 15) {
x += 1
i = 1
} else {
i += 1
}
execItem(i, x)
}
})
}
execItem(1, 1)
As a comment suggests this actually seems likely to be a problem with an asynchronous call (Tesseract...then) inside a loop. By the time the function inside then is called, your values of x and i have already moved on, so you don't get the result you expect.
One way around this would be to use a 'closure' - making a function that creates another function based on the value of i and x.
function getDisplayFunc(row, col) {
function displayRecognisedText(result) {
console.log(row, col, result.text);
//rows[row][col] = result.text;
}
return displayRecognisedText;
}
for (i = 1; i < 15; i++) {
for (x = 1; x < 15; x++) {
var take = document.getElementById("row" + i + "sm" + x);
Tesseract.recognize(take).then(getDisplayFunc(i, x));
}
}
I guess #Mike spot the error on: your code is asynchronous. What does it mean?
So, let's suppose you have this loop:
for (i = 0; i < 10; i++) {
console.log(i);
}
It will print this, right?
0
1
2
3
4
5
6
7
8
9
However, you do not print your value inside the loop directly, but as a follow-up operation to a promise. This makes this code asynchronous. It means that it does not have to execute at the exact moment you call it. I do not have Tesseract here so I will make my loop asynchronous using another very old trick, setTimeout():
for (i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 0);
}
If I run it, I get this:
10
10
10
10
10
10
10
10
10
10
What happens is, when I pass the operation we want to do (in this case, printing the i value) to an asynchronous function (recognize().then() in your case, setTimeout() in my case) through a callback (function() {console.log(i);} in my example) the asynchronous function "schedules" the operation to execute as soon as possible, but this "soon" is not faster than the loop. So, the loop finishes executing but our callback is not called, not even once! Since you are not declaring i with let, it is a global variable, so there exists only one i. And since the loop finished, the value of the i variable is 10 already.
It used to be a hard thing to solve, but with ES6 it is quite straightforward: declare i with let!
for (let i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 0);
}
The let-ed variable has a new binding at each iteration of the loop, so in practice you have 10 variables called i. The closure of your function will have access only to the one with the right value!
Maybe you should try to use while loop.
Like this:
while i < 15:
//do something
i += 1
For two variables: x, i with embeding:
while x < 15:
//do something
while i < 15:
//do something2
i += 1
x += 1
Hope I understand the problem correctly.
Im trying to simulate a Typewriter effect with javascript.
Theorically it should work with my code:
function TypeWriteToDoc(txt, id, x){
document.getElementById(id).innerHTML = document.getElementById(id).innerHTML + txt.charAt(x);
}
function TypeWrite(txt,id){
for (var i = 0; i < txt.length; i++){
setTimeout(function() {
TypeWriteToDoc(txt, id, i);
}, 1000*(i+1));
}
}
That should be it, when i call TypeWrite("example", "p_test"); it should write each character of "test" in the "p_test" html. I think the problem its not on my code since when i call the function without using setTimeout it works like in the code below:
function TypeWriteWithNoSettimeout(txt, id){
for (var i = 0; i < txt.lenght; i++){
TypeWriteToDoc(txt, id, i);}
}
This is a common issue with var in for-loops with callback functions.
The easiest solution? Just use let instead. let has support in all major browsers.
function TypeWrite(txt,id){
for (let i = 0; i < txt.length; i++){
setTimeout(function() {
TypeWriteToDoc(txt, id, i);
}, 1000*(i+1));
}
}
Similar to the previous response but rather than appending original text along with div.innerHtml, I adjusted it to be just the text char which simulates more of a typewriter feel. To increase the delay, I multiplied the index with 1000 rather than adding it since the larger increments are more visible.
function TypeWriteToDoc(txt, id, i) {
setTimeout(function() {
var div = document.getElementById(id)
div.innerHTML +=txt.charAt(i)
}, 1000 * (i))
}
function TypeWrite(txt,id){
for (var i = 0; i < txt.length; i++) {
TypeWriteToDoc(txt, id, i)
}
}
TypeWrite('example', 'p_test')
<div id="p_test"></div>
I'm trying to make a faux loading screen, and I need delays between loading messages of about 20-50ms or so so that people can actually see what's going on before it cuts to the initialized screen. The button that activates this goes to the following function:
function gameinit() {
for (k = 0; k <=1; k += 0.125) {
setTimeout(function () {
var nexttxt = "Loading... " + toString(100 * k) + "%"
}, 20);
displayupdate(nexttxt);
}
}
However this comes up as an incorrect syntax (on JSfiddle - https://jsfiddle.net/YoshiBoy13/xLn7wbg6/2/) when I use JShint - specifically lines four and five. I've looked at the guides for this and everything seems to be in order. What am I doing wrong?
(Note: displayupdate(nexttxt) updates the <p> tags with the next line of text)
When executing the script, nothing happens - the sixteen lines of text on the HTML move up as normal, the top eight being replaced with the eight generated by the gameinit() function, but the gameinit() only generates blank. If the script is executed again, it just outputs eight lines of 112.5% (as if it was the 9th iteration of the for loop).
I'm almost certain it's something elementary that I've missed, could someone please tell me what I've done wrong?
Use setInterval() instead, you can clear interval using clearInterval()
function gameinit() {
displayupdate("Loading... 0%");
var k = 0;
var inter = setInterval(function() {
if (k < 1) {
k += .25;
displayupdate("Loading... " + 100 * k + "%")
} else {
clearInterval(inter);
}
}, 2000);
}
function displayupdate(d) {
console.log(d);
}
gameinit();
here is another function can do this better ---- setInterval
var txt = '';
var time = 0;
var id = setInterval(function(){
console.log("loading..."+time/8*100+"%");
if(time++>7)
clearInterval(id);
},1000);
setTimeout doesn't work as you would expect it to work inside loops. You have to create a closure for each loop variable passed on to setTimeout, or create a new function to execute the setTimeout operation.
function gameinit() {
for (var k = 0; k <= 1; k += 0.125) {
doSetTimeOut(k);
}
}
function doSetTimeOut(k) {
setTimeout(function() {
var nexttxt = "Loading... " + toString(100 * k) + "%"
}, 20);
displayupdate(nexttxt);
}
My Javascript timer is for people with a rubiks cube with generates a scramble (nevermind all this, but just to tell you I'm generating after each solve a new scramble will be generated) and my scrambles do actually have a while (true) statement. So that does crash my script, but it 95/100 times stops just before the script crashes but I don't wanna have any times.
Let me explain a bit more detailed about the problem.
Problem: javascript crashes because my script takes too long to generate a scramble.
Below you have 3 functions I use.
This function generates a scramble with the Fisher-Yates shuffle.
Timer.prototype.generateScramble = function(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
};
This function validates the input e.g. I receive an array as the following:
Here I only have to check the first character. That's why I use the seconds [ ] notation. I don't want people get an F with an F2 e.g.
var scr = ["F","R","U","B","L","D","F2","R2","U2","B2","L2","D2","F'","R'","U'","B'","L'","D'"]
Timer.prototype.validateScramble2 = function(array) {
var last = array.length-1;
for (var i = 0; i < array.length-1; i++) {
if (array[i][0] == array[i+1][0]) {
return false;
}
}
for (var i = 0; i < array.length-2; i++) {
if (array[i][0] == array[i+2][0]) {
return false;
}
}
if (array[0][0] == [last][0]) {
return false;
}
return true;
};
The above functions are just waiting to be called. Well in the function below I use them.
Timer.prototype.updateScramble2 = function(scrambleArr, len, type) {
var self = this;
var scramble = '', j, updatedArr = [];
while (updatedArr.length < len) {
j = (Math.floor(Math.random() * scrambleArr.length));
updatedArr.push(scrambleArr[j]);
}
while (!self.validateScramble2(updatedArr)) {
updatedArr = self.generateScramble(updatedArr);
}
for (var i = 0; i < updatedArr.length; i++) {
scramble += updatedArr[i] + ' ';
}
scrambleDiv.innerHTML = scramble;
};
I assume you guys understand it but let me explain it briefly.
The first while-loop adds a random value from the given array(scrambleArr) into a new array called updatedArr.
The next while-loop calls the validateScramble2() function if there isn't in an array F next to an F2.
The for-loop adds them into a new variable added with a whitespace and then later we show the scramble in the div: scrambleDiv.innerHTML = scramble;
What do I need know after all this information?
Well I wanna know why my updateScramble2() functions lets my browser crash every time and what I do wrong and how I should do it.
I'm not entirely sure I understand the question, but from the way your code looks, I think you have an infinite loop going on. It appears as if validateScramble2 always returns false which causes your second loop in updateScramble2 to perpetually run.
I suggest you insert a breakpoint in your code and inspect the values. You could also insert debugger; statements in your code, works the same way. Open dev tools prior to doing these.
A suggestion is instead of using loops, use a timer. This breaks up your loop into asynchronous iterations rather than synchronous. This allows the browser breathing space for other operations. Here's an example of a forEachAsync:
function forEachAsync(array, callback){
var i = 0;
var timer = setInterval(function(){
callback.call(null, array[i]);
if(++i >= array.length) clearInterval(timer);
}, 0);
}
forEachAsync([1,2,4], function(item){
console.log(item);
});
You can take this further and use Promises instead of callbacks.
I have this function that causes the other functions to be skipped
I was just wondering what's wrong?
function sToLeftDiagonal(){
alert("sToLeftDiagonal");
var x, y;
var dCtr = 0;
var hLoop = varInit.maxRow;
for(var fifteen = 0; fifteen <= 3; fifteen++){
x = 0;
y = 5 - fifteen;
for(var xy = 0; xy <= hLoop ; xy++){
if (board[y][x] == player){
alert("plus");
dCtr++;
}else{
alert("negative");
dCtr = 0;
}
if (dCtr == varInit.cWins) {
dWinner(player);
}
x++;
y--;
}
hLoop--;
}
alert("end diagonal");
}
I've placed a lot of 'alert' to check whether they are executed or not, apparently
alert("end diagonal");
is not executed thus skips the next function in the main program
i know this is simple, i think i'm just overlooking some things..
thanks
i figured out what was causing the function to stop unexpectedly and not reach the last alert. it's because the values of [y] and [x] are wrong as i tried alerting every array index that the function goes through and variable y had an index of [-2] which wasn't suppose to be there.