Setting image src is not async in setInterval - javascript

I am creating an animation by using setInterval.
var roman_numeral = document.getElementById('roman_numeral');
var i = 1
var generation = 1
var preload;
setInterval( async function (a) {
roman_numeral.innerHTML = romanize(i);
console.log(i);
if(i == 1){
preload = new Preloader(generation+1, "generation")
console.log("The code stops here");
//The code waits here; Seems like synchronus
}
i++
if(i == 1000){
i = 1;
generation ++;
preload.add()
}
if(generation == 1035){
i = 1;
generation = 1
}
}, 10)
I made a class for preloading images, but when creating a new instance of the class, the setInterval seems to run synchronus.
class Preloader {
constructor(gen, attach_id) {
this.gen = gen
this.attach_id = attach_id
this.preload();
}
async preload() {
let container = document.getElementById("generation_animation");
let preload_img = document.createElement("img");
preload_img.style.display = "none";
preload_img.style.width = "0px";
preload_img.id= "preload_generation";
preload_img.setAttribute("loading", "lazy")
container.appendChild(preload_img);
preload_img.src = "res/img/Generations/" + this.gen.toString() + ".png";
container.appendChild(preload_img)
console.log("aaaaaaaa");
}
add() {
let previous = document.getElementById("generation")
let current = document.getElementById("preload_generation");
current.style.width = "50%";
current.style.display = "";
current.classList.add("generations_class");
current.id = "generation";
previous.remove();
}
}
I want to load the image while performing the setInterval loop. How would i do that?

Related

Why I get Indefined when displaying Img’s on page?

I have been playing with this code for a while and I was wondering why when I try to add img’s to the array on the js code makes the images appear on DOM but also makes a bunch of Undefined elements appear, How can I just make the 15 images appear without the undefined? Thanks
enter link description here
var previous = document.getElementById('btnPrevious')
var next = document.getElementById('btnNext')
var gallery = document.getElementById('image-gallery')
var pageIndicator = document.getElementById('page')
var galleryDots = document.getElementById('gallery-dots');
var images = ["https://exoplanets.nasa.gov/internal_resources/1763/",
"https://cdn.britannica.com/56/234056-050-0AC049D7/first-image-from-James-Webb-Space-Telescope-deepest-and-sharpest-infrared-image-of-distant-universe-to-date-SMACS-0723.jpg",
"https://assets.newatlas.com/dims4/default/ac389ce/2147483647/strip/true/crop/1620x1080+150+0/resize/1200x800!/quality/90/?url=http%3A%2F%2Fnewatlas-brightspot.s3.amazonaws.com%2Farchive%2Funiverse-expanding-acceleration-1.jpg",
"https://media.newyorker.com/photos/590966ee1c7a8e33fb38d6cc/master/w_2560%2Cc_limit/Nissan-Universe-Shouts.jpg",
"https://www.thoughtco.com/thmb/NY5k_3slMRttvtS7mA0SXm2WW9Q=/1500x0/filters:no_upscale():max_bytes(150000):strip_icc()/smallerAndromeda-56a8ccf15f9b58b7d0f544fa.jpg",
"https://static.scientificamerican.com/sciam/cache/file/05B8482C-0C04-4E41-859DCCED721883D2_source.jpg?w=590&h=800&7ADE2895-F6E3-4DF4-A11F51B652E9FA88",
"https://qph.cf2.quoracdn.net/main-thumb-66277237-200-huqebnzwetdsnnwvysbxemlskpcxnygf.jpeg",
"http://www.pioneertv.com/media/1090/hero_shot_1080x720.jpg?anchor=center&mode=crop&width=600&height=400&rnd=133159257140000000",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRSWFW1EpMNFM5-dbZEUUnzJkzT3KbUCeuhPHx_eseFCpPeX4Q_DIVPopjS0LeKVmKdQho&usqp=CAU",
"https://cdn.mos.cms.futurecdn.net/rwow8CCG3C3GrqHGiK8qcJ.jpg",
"https://static.wixstatic.com/media/917d103965314e2eacefed92edb6492c.jpg/v1/fill/w_640,h_356,al_c,q_80,usm_0.66_1.00_0.01,enc_auto/917d103965314e2eacefed92edb6492c.jpg",
"https://astronomy.com/~/media/A5B9B6CF36484AB9A6FFAE136C55B355.jpg",
"https://discovery.sndimg.com/content/dam/images/discovery/fullset/2022/9/alien%20planet%20GettyImages-913058614.jpg.rend.hgtvcom.616.411.suffix/1664497398007.jpeg",
"https://images.newscientist.com/wp-content/uploads/2017/06/21180000/planet-10-orange-blue-final-small.jpg?crop=16:9,smart&width=1200&height=675&upscale=true",
"https://images.hindustantimes.com/img/2022/07/20/1600x900/Viral_Instagram_Planet_Rainbow_Nasa_1658316556293_1658316573815_1658316573815.PNG"
]
for (var i = 0; i < 15; i++) {
images.push({
title: "Image " + (i + 1),
source: images[i]
});
}
var perPage = 8;
var page = 1;
var pages = Math.ceil(images.length / perPage)
// Gallery dots
for (var i = 0; i < pages; i++){
var dot = document.createElement('button')
var dotSpan = document.createElement('span')
var dotNumber = document.createTextNode(i + 1)
dot.classList.add('gallery-dot');
dot.setAttribute('data-index', i);
dotSpan.classList.add('sr-only');
dotSpan.appendChild(dotNumber);
dot.appendChild(dotSpan)
dot.addEventListener('click', function(e) {
var self = e.target
goToPage(self.getAttribute('data-index'))
})
galleryDots.appendChild(dot)
}
// Previous Button
previous.addEventListener('click', function() {
if (page === 1) {
page = 1;
} else {
page--;
showImages();
}
})
// Next Button
next.addEventListener('click', function() {
if (page < pages) {
page++;
showImages();
}
})
// Jump to page
function goToPage(index) {
index = parseInt(index);
page = index + 1;
showImages();
}
// Load images
function showImages() {
while(gallery.firstChild) gallery.removeChild(gallery.firstChild)
var offset = (page - 1) * perPage;
var dots = document.querySelectorAll('.gallery-dot');
for (var i = 0; i < dots.length; i++){
dots[i].classList.remove('active');
}
dots[page - 1].classList.add('active');
for (var i = offset; i < offset + perPage; i++) {
if ( images[i] ) {
var template = document.createElement('div');
var title = document.createElement('p');
var titleText = document.createTextNode(images[i].title);
var img = document.createElement('img');
template.classList.add('template')
img.setAttribute("src", images[i].source);
img.setAttribute('alt', images[i].title);
title.appendChild(titleText);
template.appendChild(img);
template.appendChild(title);
gallery.appendChild(template);
}
}
// Animate images
var galleryItems = document.querySelectorAll('.template')
for (var i = 0; i < galleryItems.length; i++) {
var onAnimateItemIn = animateItemIn(i);
setTimeout(onAnimateItemIn, i * 100);
}
function animateItemIn(i) {
var item = galleryItems[i];
return function() {
item.classList.add('animate');
}
}
// Update page indicator
pageIndicator.textContent = "Page " + page + " of " + pages;
}
showImages();
I checked your code and make it work with a small modification.
You are reusing the same array with the links of images and push inside the new object with the shape of { title, source }.
You just need to do this changes:
Change the name of your array of images. Something from images to arrayOfImages.
const arrayOfImages = ["https://exoplanets.nasa.gov/internal_resources/1763/", ...]
Declare an empty array before your first for loop. Make something like const images = []
On your for loop, instead of loop over the images variable, do it over the arrayOfImages variable.
const images = [];
for (var i = 0; i < 15; i++) {
images.push({
title: "Image " + (i + 1),
source: arrayOfImages[i]
});
}
With those changes, everything works for me.
Also, as a recommendation, try to avoid the var keyword. If you want more details about this, this answer is very helpful: https://stackoverflow.com/a/50335579/17101307
You can use Array#map to create a new array of objects from the array of URLS, then replace the original array.
images = images.map((x, i) => ({
title: "Image " + (i + 1),
source: x
}));

Javascript chaining window.onload functions

I have a javascript function that grabs a dataset numeric value and appends it to an XMLhttprequest parameter. It has to run onload as the content is printed dynamically through php.
I now am trying to create a simple carousel for the elements printed and finding some difficulty chaining onload functions.
I've found creating an additional onload function for anything breaks the first onload function. What can I do here?
function userData() {
let infoWrap = document.querySelector(".agent-detail-info").dataset.id;
console.log(infoWrap);
return infoWrap;
}
window.onload = userData;
window.onload = () => {
const request = new XMLHttpRequest();
request.open(
"GET",
`url&usertolookup=${userData()}`
);
request.onload = function () {
let response = request.response;
let parsedData = JSON.parse(response);
console.log(parsedData);
let testimonials = parsedData.data.testimonials.details;
testimonials.forEach((testimonial, index) => {
const testimonialWrap = document.querySelector(".testimonials");
// Create testimonials container
let innerTestimonials = document.createElement("div");
innerTestimonials.className = "inner-testimonial-container";
testimonialWrap.appendChild(innerTestimonials);
// Create star rating container
let starWrap = document.createElement("div");
starWrap.className = "testimonial-stars";
innerTestimonials.appendChild(starWrap);
// Create Testimonial Content
let innerTestimonialParagraph = document.createElement("p");
innerTestimonials.appendChild(innerTestimonialParagraph);
// Create Testimonial Signature
let innerTestimonialSignature = document.createElement("address");
innerTestimonials.appendChild(innerTestimonialSignature);
// Loop through rating value and create elements
let rating = testimonial.rating;
for (let i = 0; i < rating; i++) {
let star = document.createElement("i");
star.className = "fa fa-star";
starWrap.appendChild(star);
}
// Insert Testimonial Content
let testimonialText = testimonial.Testimonial;
innerTestimonialParagraph.innerHTML = testimonialText;
// Insert Testimonial Signature
let signature = testimonial.Signature;
innerTestimonialSignature.innerHTML = signature;
});
};
request.send();
};
Testing Carousel (have tried alternative with event listeners rather than inline onclick and cannot access the elements printed through the response(returns undefined as the elements are printed after dom load))
let tabIndex = 1;
function nextTestimonial(n) {
testimonialSlide((tabIndex += n));
}
function currentTestimonial(n) {
testimonialSlide((tabIndex = n));
}
function testimonialSlide(n) {
let innerTestimonials = document.querySelectorAll(
".inner-testimonial-container"
);
if (n > innerTestimonials.length) {
tabIndex = 1;
}
if (n < 1) {
tabIndex = innerTestimonials.length;
}
for (let i = 0; i < innerTestimonials.length; i++) {
innerTestimonials[i].style.display = "none";
}
innerTestimonials[tabIndex - 1].style.display = "block";
}
Random attempt to chain onload functions (this breaks the response)
window.onload = () => {
const innerTestimonialsNew = document.querySelectorAll(
".inner-testimonial-container"
);
console.log(innerTestimonialsNew);
};

Loader dissapears but image not rendered entirely

I have quite a few static photos on my page. My goal is to show a loader while the page and the image loads. The problem is after my loader disappears, the image is not fully rendered yet.
How can I make the loader disappear after the images fully rendered?
Here is my current attempt from a different source.
Javascript:
(function(){
function id(v){return document.getElementById(v); }
function loadbar() {
var ovrl = id("overlay"),
prog = id("progress"),
stat = id("progstat"),
img = document.images,
c = 0;
tot = img.length;
function imgLoaded(){
c += 1;
var perc = ((100/tot*c) << 0) +"%";
prog.style.width = perc;
stat.innerHTML = "Loading "+ perc;
if(c===tot) return doneLoading();
}
function doneLoading(){
ovrl.style.opacity = 0;
setTimeout(function(){
ovrl.style.display = "none";
}, 1200);
}
for(var i=0; i<tot; i++) {
var tImg = new Image();
tImg.onload = imgLoaded;
tImg.onerror = imgLoaded;
tImg.src = img[i].src;
}
}document.addEventListener('DOMContentLoaded', loadbar, false);}());
You're missing the image in the body
...
function doneLoading(){
ovrl.style.opacity = 0;
setTimeout(function(){
ovrl.style.display = "none";
}, 1200);
//you should put
document.body.appendChild(this);
}
...

javascript stops responding while taking video player current time

var startTime = parent.startTime;
var endTime = parent.endTime;
var divID = '#'+parent.divId;
var description = parent.description;
do {
var currentTime1 = $('video').get(0).currentTime;
if(currentTime1 >= startTime) {
console.log('in if');alert('hi');
parent.$(divID).append(description);
}
setTimeout(function(){$('video').get(0).currentTime = $('video').get(0).currentTime + 1; currentTime1 = parseInt($('video').get(0).currentTime); }, 1000);
} while (currentTime1 <= endTime);
parent.$(divID).empty(); console.log('at end');
the above code stops responding and debuger shows this line var currentTime1 = $('video').get(0).currentTime;
Your code gets to infinite loop, because of
do {
var currentTime1 = $('video').get(0).currentTime;
} while (currentTime1 <= endTime);
It's executed as fast as your browser allows, so it get's stuck, because setTimeout will be executed after 1s and your currentTime1 will never change.
Please change logic - use video events, like timeupdate
var startTime = parent.startTime;
var endTime = parent.endTime;
var divID = '#'+parent.divId;
var description = parent.description;
var myVar = setInterval(check,1000);
function check()
{
var currentTime1 = parseInt($('video').get(0).currentTime);
if(currentTime1 >= parent.endTime)
{
clearInterval(myVar);
parent.$(divID).empty();
}
else if(currentTime1 >= parent.startTime)
{
parent.$(divID).empty();
parent.$(divID).append(description);
}
}
this code works without loop construct. setInterval() works for repeating the action again and again.

Using a 'for' loop. How do I subtract from value 'i' using an if statement?

I am using a script that uses a for loop to spawn objects within Unity. When the player object hits one of these spawned objects it calls a function that makes a boolean true. When this boolean is true it should subtract 1 from the for loop. Basically the for loop has a max of 10, when an object is spawned it adds one, and I want it to subtract 1 when an object is struck by the player. I am having issues trying to make this work. Any and all help, greatly appreciated.
var theObject:GameObject;
var maxPos:float = 500;
var minPos:float = -500;
var max = 10;
var switch1 = false;
function Start(){
StartCoroutine(spawn());
}
function spawn() : IEnumerator {
for (var i = 0; i < max;){
if (switch1 == true){
i--;
}
else if (switch1 == false){
i++;
//Debug.Log("spawn");
//Time between spawns
yield WaitForSeconds(0.4);
//Determines and spawns new object
var theNewPos = new Vector3(Random.Range(minPos,maxPos),0,Random.Range(minPos,maxPos));
var go : GameObject = Instantiate(theObject);
go.transform.position = theNewPos;
}
else{
switch1 = false;
}
}
}
function AtomHit(){
switch1 = true;
}
I guess you are trying to do this:?
var theObject:GameObject;
var maxPos:float = 500;
var minPos:float = -500;
var max = 10;
var switch1 = false;
function Start(){
StartCoroutine(spawn());
}
function spawn() : IEnumerator {
for (var i = 0; i < max;){
if (switch1){
i--;
}
else{
i++;
//Determines and spawns new object
var theNewPos = new Vector3(Random.Range(minPos,maxPos),0,Random.Range(minPos,maxPos));
var go : GameObject = Instantiate(theObject);
go.transform.position = theNewPos;
}
//Time between spawns
yield WaitForSeconds(0.4);
switch1 = false;
}
}
function AtomHit(){
switch1 = true;
}

Categories