How to make a text animation with javascript - javascript

I want to make a couple of texts appear one by one with a javascript interview, i want each word to pop up one after the other and have the texts appear in 4 different lines and would like to know the best way to go about it as a starter with the language. I saw the following code online but would prefer one i can tell what it does clearly (if else statements and the sorts):
(function animate() {
str.length > 0 ? el.innerHTML += str.shift() : clearTimeout(running);
let running = setTimeout(animate, 90);
// let runnin = setTimeout(animate, 90);
})();
I tried working with this to have another text with the same animation but can't seem to get the other to come up only when the first array of words have been completed by doing this to a different function, but it didn't work out like I'd hoped
(function ani() {
if(animate()==false){
str2.length > 0 ? ell.innerHTML += str2.shift() : clearTimeout(runnin);
let run = setTimeout(ani, 90);
}
})();

Related

How to do a task outside of draw loop in p5js

I'm trying to convert an image into a picture that only has a certain amount of colors in p5.js. I am doing this by picking num random colors. Then, I'm going through every pixel in the image with loadPixels() and giving it a score. This score is determined by how close the color is to one of the random colors. I do this by adding the difference individually from the rgb values and then choosing the lowest score. For example, if I had num = [color(100, 100, 100), color(200, 200, 200)] and I was looking at a pixel that has color(100, 150, 110) then the score would be not 240 (the difference between the image pixel and the 200 color) but instead 60. This all works fine. Next, what I'm trying to do is make sure that every pixel has a score under scoreBoundary. Originally, this variable is set to 0. If the score of a pixel is more than scoreBoundary, I alter the closest random color to bring the pixel's score under scoreBoundary. This all should work fine. After a few loops (I haven't decided how many yet, maybe it has to do with the average pixel score or something), if there is still a pixel over scoreBoundary, I increase scoreBoundary. Eventually, I should have the best picture I can have with num colors. (If you want to know, I'm trying to make a sort of Cross-Stitch Clone.)
Now for my problem. I want to make a temporary progress bar, because this method is very slow. Originally, I tried putting text that said pixelNum + " out of " + pixels.length. However, since this process was in a for loop, this didn't show up. So, I tried putting this process in the draw loop. Now the text shows up, but it's unbearably slow. After about a minute, I was maybe 1% done with the first loop (and remember, there will be thousands) because it was only performing one calculation per frame. Now I ask you two things, and either solution helps.
One, is there a way to have a process that works as fast as it can away from the draw loop? For example, can I have this process run multiple times per frame (without just adding i < previousBoundary * howMuchFasterIWantItToBe) while still being linked to draw for the progress bar?
Two, is there another way to go about this? Another library or method that reduces the number of colors in an image to num?
You don't really show any code that is reproducible to explain what issue you are having.
In any case, what you are looking for (for your first question) is an async function.
SEIZURE WARNING FOR PHOTOSENSITIVITY
Seriously, this example sketch will wreck your eyes but you can see two ellipses working on different schedules because of the async function
Importantly, I had to append the start of the sketch with /*jshint esversion: 9 */ for the editor to allow async to be used:
/*jshint esversion: 9 */
let thing = 10;
let thing2 = 10;
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
drawOther();
for(let i = 0; i < 1000; i++){
if(thing <= 400){
thing += 2;
}else{
thing = 10;
}
fill(255)
stroke(0);
ellipse(width, height, thing, thing);
}
}
const drawOther = async () => {
for(let i = 0; i < 100; i++){
if(thing2 <= 400){
thing2 += 2;
}else{
thing2 = 10;
}
fill(0);
stroke(255)
ellipse(0, 0, thing2, thing2);
}
}
You can read more about async functions here but basically, it does what you want - to launch a separate thread of activity that won't block your main loop.
If you want to return anything from an async function you would need to read about await and promises as well.

JavaScript script creating a list of three numbers

I’m new here, and so on coding.
I friend of mine suggests me to learn JavaScript and Python, because I love riddles that I can’t solve (so this languages could help me).
Let me explain: I want to create a JS script starting from this real-life problem.
I have a padlock which have a code of three numbers to be unlocked (you have to turn upside down these numbers to obtain the “Open sesame”), the code goes to 000 to 999, obviously.
I need to create a script that lists all the possible numbers and, at the end, also tell me how many different numbers I have (I suppose 1000 if my math isn’t bad as my english).
I started the learning path, but I’m not able to create this script.
I need to check all the different combinations that i have done for unlock the padlock
Can someone help me?
Thank you so much
ps: it could be nice also the same script in bash, which it's more familiar to me
x 0stone0: I have non familarity with JavaScript, I've only done an online course, so I made no attempt, just asking.
For bash, I found right here a "skeleton" of permutation script like this:
for X in {a..z}{a..z}{0..9}{0..9}{0..9}
do echo $X;
done
but I really don't know ho to edit it, cause I don't know hot to save the output of three numbers YYY from 0 to 9
Javascript
let i = 0;
while (i <= 999) {
console.log(String(i).padStart(3, '0'));
i++;
}
Pad a number with leading zeros in JavaScript
Bash
for X in {0..9}{0..9}{0..9}; do
echo $X;
done
Try it online!
Using js, you can do:
let count = 0;
for (let i = 0; i <= 999; i++) {
count++ // count++ is the same as count = count + 1, count is used to count the number of times the loop has run
if (i < 10) { // if i is less than 10 add two zero before it, for it to look like (009)
console.log('00' + i);
} else if (i < 100) { // if i is less than 100 add one zero before it, for it to look like (099)
console.log('0' + i);
} else if (i < 1000) { // if i is less than 1000 add nothing before it, for it to look like (999)
console.log(i);
} else {
console.log(i);
}
}
// then we console.log() the count variable
console.log(`There is ${count} possibilities`);
The program is made to show 3 digits, so if it's 9, it will show 009 and same for 99 => 099

If an elements style.left reaches something, change style.left to something else

I'm currently working on creating a simple interactive CV, with mainly javascript. The idea is that the user steers a character to the right and then a few "about me"-divs will show up. These "about-me"-divs are supposed to move when the character moves, so it looks like they're getting closer to/further away from them. If unclear, check the demo.
I've fixed this by setting style.left to 100, and then subtracting from it each time the character moves to the right. In the example I've used minions, instead of "about-me"-divs, just to get the function to work.
let moveMinion = 100; // This is the same as their 'left' in CSS.
let moveMinionTwo = 150;
if (keyPresses.ArrowRight) {
moveMinion -= 0.3;
moveMinionTwo -= 0.3;
minionOne.style.left = moveMinion + '%'; // I Used % because I want it to work on different screen widths.
minioneTwo.style.left = moveMinionTwo + '%'; }
However I want the "about me"-divs to "repeat" and come back again, after the character have walked for a bit. Like this example.
I tried using this code underneath, in the same function ofc, but nothing happens, except it seems like the minion blinks quickly when style.left is -10%.
if (minionOne.style.left <= -10 + '%') minionOne.style.left = moveMinion + '%';
TLDR: I want style.left to change to something else when style.left hits a specific number.
Bear in mind, this is not finished yet, so you don't have to judge the code and the project outside of the one I need help with, unless you want to give any tips.
Repo on github
My demo
You can't <= strings.
You gotta convert one to a number and compare to a number.
const threshold = -10;
const asNum = Number(minionOne.style.left.split('%')[0]);
if (asNum <= threshold ) {
minionOne.style.left = `${100 + asNum - threshold}%`;
}

Java Script + Node.js Calculator issue

I am a "new" developer into the foray of Web Development and I have come across an issue I was hoping that you fine people on Stack Overflow would be able to help me with. I have asked several Cadre and Instructors in my class and we are all stumped by it.
To start with I have decided to put all of my code on a Gitlab repo so if you want to look at the whole thing (or if you want to add to it let me know): Link to Github Repo. I fiqured you guys don't want the whole thing posted as a wall of text and rather some snip-its of what in the file I specifically. But it is relitively small file
I am useing simple JavaScript as well as Node.Js to be able to build a working calculator in the back end that I can use as a template for any other project I will need to work on in the future. For now I am trying to just get it working by imputing things via the console.
I have made a way for what is imputed in Node and to an imputArray var I have set up and the Array goes something like this:
[(command), (num1), (num2), (num3), ...]
I set up a switch function that runs a block of code based on what command was given (add, subtract, divide, etc..). As well as separating the command from the number and putting them inside another array.
The part I need some help with is with getting the block of code to work for what I want it to do. I have got it set up to run rather easily on two numbers but I want it to handle as many numbers as I want to throw at it. I tried various forms of for loops as well as forEach loops and I cant seem to get it working.
case 'divide':
for (i = 1; i < numArray.length; i++) { // If any number besides the first is 0 spit out this
if (numArray[i] === 0) {
consol.log("You canot divide by zero!");
}
else {
var previousTotal = numArray[0]; //Inital number in array
for (i = 1; i < numArray.length; i++) {
previousTotal = previousTotal / numArray[i]; // for each number in array divide to the previous number
}
}
result = previousTotal // Pushes end total to result
}
break;
I have gone through several different versions of the above code (such as using for loops instead) but this is pretty much what I ended up with. I'm sure there is an easier way and more sane way to do what I am trying to do, but if I knew how I wouldn't be here.
Essentially this is the ideal thing I want to do but I cant find a way to do it: I want to run a small block of code the index of the number array, minus one. In this case it is dividing the previous number by the next number in the array.
So it only runs if there are more then one in the array and it does the function to the previous number, or total from the last one in the array.
This is pretty much the only thing holding me back from finishing this so if someone can take the time to look at my crapy code and help it do what I want it to do that would be awesome.
Your code is reseting result each time the outer loop iterates so it will just equal what ever the last prev Total is. Basically every loop but the last is irrelevant. Do you want to add them to result? If so you want:
result += previousTotal
Or if you want an array of the answers you want:
result.push(reviousTotal)
Sorry not 100% what you want. Hope this helps!
You just need one loop, and you probably want to stop iterating if a 0 occurs:
result = numArray[0]; //no need for another variable
for (var i = 1; i < numArray.length; i++) { // declare variables!
if (numArray[i] === 0) {
console.log("You canot divide by zero!"); // typo...
break; // exit early
}
result = result / numArray[i];
}
For sure that can be also written a bit more elegantly:
const result = numArray.reduce((a, b) => a / b);
if(isNaN(result)) {
console.log("Can't divide by zero!");
} else {
console.log(`Result is ${result}`);
}
I assume you want the divide command to do ((num1/num2)/num3)/...
There are couple of issues in the code you posted, I will post a version that does the above. You can inspect and compare it your version to find your mistakes.
// divide, 10, 2, 5
case 'divide':
if (numArray.length < 2) {
console.log("no numbers in array")
break;
}
// previousTotal starts with 10
var previousTotal = numArray[1];
// start from the second number which is 2
for (i = 2; i < numArray.length; i++) {
if (numArray[i] === 0) {
console.log("You canot divide by zero!");
}
else {
previousTotal = previousTotal / numArray[i]; // for each number in array divide to the previous number
}
}
result = previousTotal;
// result will be (10/2)/5 = 1
break;

Counting up using jquery

So far I have a little script that detects the scroll top position and at a set level I want it to trigger a jquery counter. So far I have an array with the maximum number inside var = eightyS = [3]; then there is..
if (y > 630) {
$('.targetS').each(function() {
//counter
delay(1000);
});
} else {
return false;
}
Now I've made something similar in C++ years ago (couldn't do it now with a gun to my head) so I followed a similar logic. But this is where I'm stuck. The idea behind this function is that it will do a read out on screen of 0 then 1 then 2 then 3. Any help is greatly appreciated
You could use a setInterval() which executes a function ever second such as below:
var count = 0;
var interval = setInterval(function(){
count++;
$('#counter').text(count);
}, 1000);
I've created a quick JSFiddle
You should be able to wrap this in to your code fairly easily. You may also want to use clearInterval(interval) to stop the function executing when you scroll back up the page; or when you get in to your else block, which would have the same effect. I've added a clearInterval() example to the JSFiddle on click of the stop link. You'll need to make sure the interval variable is in scope when clearing it.

Categories