Trouble getting setInterval and setTimeout to work - javascript

This uses Raphaeljs to draw a single chord from an array:
function createChordStruct(key, string, shape) {
var string = string.toUpperCase();
var position = positions[string][key];
var struct = chord_shapes[shape];
return {
name: key + struct.name,
chord: struct.chord,
position: position,
position_text: struct.position_text,
bars: struct.bars
}
}
function createChordElement(chord_struct) {
var chordbox = $('<div>').addClass('chord');
var chordcanvas = $('<div>');
var chordname = $('<div>').addClass('chordname');
chordbox.append(chordcanvas);
chordbox.append(chordname);
chordname.append(chord_struct.name);
var paper = Raphael(chordcanvas[0], 150, 140);
var chord = new ChordBox(paper, 30, 30);
chord.setChord(
chord_struct.chord,
chord_struct.position,
chord_struct.bars,
chord_struct.position_text);
chord.draw();
return chordbox;
}
function createSectionElement(section_struct) {
var section = $('<div>').addClass('section');
var section_title = $('<div>').addClass('title');
var section_desc = $('<div>').addClass('description');
section.append(section_title);
section.append(section_desc);
section_title.append(section_struct.section);
section_desc.append(section_struct.description);
return section;
}
And this takes each chord created from the array and puts them in a new div called "chordscroller":
function c_i() {
var randomholder = 'id_' + (Math.floor(Math.random() * 100005) + 1);
var randomId = 'id_' + (Math.floor(Math.random() * 100005) + 1);
$(function () {
$('#sortable').append($('<li id ="' + randomholder + '" class="chordbox"><span id="i" class="scale">C - I</span><span id="' + randomId + '" class=" even scrollpane chordscroller"></span></li>').sortable( "refresh" ))
});
function c_one() {
var container = $("#" + randomId + "");
var column = null;
var column = _.shuffle(c_1);
for (var i = 0; i < column.length; ++i) {
var section_struct = column[i];
var section = createSectionElement(section_struct);
for (var j = 0; j < section_struct.chords.length; ++j) {
section.append(createChordElement(section_struct.chords[j]));
}
container.append(section);
}
}
$(function() { c_one() });
}
The problem is it draws all the chords at the same time and it takes forever. I've tried every combination of setTimeout and setInterval I could think of but I keep running into errors.
Can anybody tell from this code how to get the chords to be drawn one at a time instead of all at once?

Finally figured it out (using a plugin called doTimeout):
$.doTimeout( 1, function() {
chord.setChord(
chord_struct.chord,
chord_struct.position,
chord_struct.bars,
chord_struct.position_text);
chord.draw();
});

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
}));

Can I update a jS variable's property dynamically from another variable?

I'm trying to update a property of a jS variable using the scroll velocity which I'm storing in another variable. This is my code thus far (scroll to the second code box as the first part works correctly):
jQuery( document ).ready(function() {
jQuery('main').attr('id', 'grained');
(function (window, doc) {
"use strict";
function grained(ele, opt) {
var element = null,
elementId = null,
selectorElement = null;
if (typeof ele === 'string') {
element = doc.getElementById(ele.split('#')[1]);
}
if (!element) {
console.error('Grained: cannot find the element with id ' + ele);
return;
} else {
elementId = element.id;
}
//set style for parent
if (element.style.position !== 'absolute') {
element.style.position = 'relative';
}
element.style.overflow = 'hidden';
var prefixes = ["", "-moz-", "-o-animation-", "-webkit-", "-ms-"];
//default option values
var options = {
animate: true,
patternWidth: 100,
patternHeight: 100,
grainOpacity: 0.1,
grainDensity: 1,
grainWidth: 1,
grainHeight: 1,
grainChaos: 0.5,
grainSpeed: 20
};
Object.keys(opt).forEach(function (key) {
options[key] = opt[key];
});
var generateNoise = function () {
var canvas = doc.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = options.patternWidth;
canvas.height = options.patternHeight;
for (var w = 0; w < options.patternWidth; w += options.grainDensity) {
for (var h = 0; h < options.patternHeight; h += options.grainDensity) {
var rgb = Math.random() * 256 | 0;
ctx.fillStyle = 'rgba(' + [rgb, rgb, rgb, options.grainOpacity].join() + ')';
ctx.fillRect(w, h, options.grainWidth, options.grainHeight);
}
}
return canvas.toDataURL('image/png');
};
function addCSSRule(sheet, selector, rules, index) {
var ins = '';
if (selector.length) {
ins = selector + "{" + rules + "}";
} else {
ins = rules;
}
if ("insertRule" in sheet) {
sheet.insertRule(ins, index);
} else if ("addRule" in sheet) {
sheet.addRule(selector, rules, index);
}
}
var noise = generateNoise();
var animation = '',
keyFrames = ['0%:-10%,10%', '10%:-25%,0%', '20%:-30%,10%', '30%:-30%,30%', '40%::-20%,20%', '50%:-15%,10%', '60%:-20%,20%', '70%:-5%,20%', '80%:-25%,5%', '90%:-30%,25%', '100%:-10%,10%'];
var pre = prefixes.length;
while (pre--) {
animation += '#' + prefixes[pre] + 'keyframes grained{';
for (var key = 0; key < keyFrames.length; key++) {
var keyVal = keyFrames[key].split(':');
animation += keyVal[0] + '{';
animation += prefixes[pre] + 'transform:translate(' + keyVal[1] + ');';
animation += '}';
}
animation += '}';
}
//add animation keyframe
var animationAdded = doc.getElementById('grained-animation');
if (animationAdded) {
animationAdded.parentElement.removeChild(animationAdded);
}
var style = doc.createElement("style");
style.type = "text/css";
style.id = 'grained-animation';
style.innerHTML = animation;
doc.body.appendChild(style);
//add custimozed style
var styleAdded = doc.getElementById('grained-animation-' + elementId);
if (styleAdded) {
styleAdded.parentElement.removeChild(styleAdded);
}
style = doc.createElement("style");
style.type = "text/css";
style.id = 'grained-animation-' + elementId;
doc.body.appendChild(style);
var rule = 'background-image: url(' + noise + ');';
rule += 'position: absolute;content: "";height: 300%;width: 300%;left: -100%;top: -100%;';
pre = prefixes.length;
if (options.animate) {
while (pre--) {
rule += prefixes[pre] + 'animation-name:grained;';
rule += prefixes[pre] + 'animation-iteration-count: infinite;';
rule += prefixes[pre] + 'animation-duration: ' + options.grainChaos + 's;';
rule += prefixes[pre] + 'animation-timing-function: steps(' +options.grainSpeed + ', end);';
}
}
//selecter element to add grains
selectorElement = '#' + elementId + '::before';
addCSSRule(style.sheet, selectorElement, rule);
}
window.grained = grained;
//END
})(window, document);
// Here down is the important part //
var grainOptions = {
animate: true,
patternWidth: 100,
patternHeight: 100,
grainOpacity: 0.04,
grainDensity: 1,
grainWidth: 1,
grainHeight: 1
};
grained('#grained', grainOptions);
document.querySelector("body").addEventListener("wheel", scrollGlitch);
function scrollGlitch(event) {
var y = event.deltaY;
var scaleY = y;
var divider = 100;
var sum = scaleY / divider;
console.log(sum);
}
});
From this I am getting 2 things which I need:
the property value of grainOpacity;
the scroll velocity as stored in the variable sum (which is divided by 100 to make the values the right scale i.e 0.01 - 0.1;
What I need to do now is update the grainOpacity property of the grainOptions variable with the value of the sum variable. Is this possible? How would I achieve this, I read about Bracket/Dot notations but can't tell if this is the right way.
You can take any object field reference using dot like
grainOptions.grainOpacity
Then you can redefine field value as using let variables.
Update your scrollGlitch function:
function scrollGlitch(event) {
var y = event.deltaY;
var scaleY = y;
var divider = 100;
var sum = scaleY / divider;
grainOptions.grainOpacity = sum;
}
Note. In JS you can take Object fields' value with 2 ways:
With saving reference on field to update it's own value. Ex:
grainOptions.grainOpacity.
Only for take value. Ex:
grainOptions['grainOpacity']

Trying to load a random link out of array

I know this is a very noob question, looked up a couple of examples but me being a beginner I'm having trouble implementing it in my code.
I think the title is pretty clear cut, I would like that the loop starts with a random item, and continues picking random items out of the array.
var bgImageArray = [
"link1" , "link2" , "link3"
]
base = "https://lh3.googleusercontent.com/pw/";
bgImageArray.forEach(function(img){
new Image().src = base + img;
});
function backgroundSequence() {
window.clearTimeout();
var k = 0;
for (i = 0; i < bgImageArray.length; i++) {
setTimeout(function(){
document.getElementById('animated-bg').style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center";
if ((k + 1) === bgImageArray.length) { setTimeout(function() { backgroundSequence() }, (60000 / tempo.value))} else { k++; }
}, (60000 / tempo.value) * i)
}
}
``
use this code for select random element from array
var bgImageArray = ["link1", "link2", "link3"];
const random = Math.floor(Math.random() * bgImageArray.length);
console.log(random, bgImageArray[random]);
Perhaps better like this
Update: Missed the random part
let bgImageArray = ["link1", "link2", "link3"];
const base = "https://lh3.googleusercontent.com/pw/";
bgImageArray = bgImageArray.map(img => new Image().src = base + img);
function backgroundSequence() {
const rndImageSrc = bgImageArray[Math.floor(Math.random()*bgImageArray.length)].src;
document.getElementById('animated-bg').style.background = "url(" + rndImageSrc + ") no-repeat center center";
}
let tId = setInteval(backgroundSequence,tempo*1000);

Trouble hiding/showing divs in using DOM/js/css

I am trying to make a debugger that will be dynamiaclly created with some variables. The names on the left div need to show a div for the corresponding variables Description,Variable ID, and initial Value as well as another div that will show history and lock status when variables are updated later. Where I am having trouble is properly adding the show/hide to the dom I think. Everything starts hidden and then when I click a name the Variables for that name show up but the next click doesn't hide the values from the former. Also any cleanup/optimization advice?
<script type="text/javascript">
var variableIDArray = {};
function loadVariables(variables) {
if (typeof variables != "object") { alert(variables); return; }
var namearea = document.getElementById('namearea');
var description = document.getElementById('description');
var varid = document.getElementById('varid');
var initialvalue = document.getElementById('initialvalue');
var valuelock = document.getElementById('valuelock');
for (var i = 0; i < variables.length - 1; i++) {
var nameDiv = document.createElement('div');
nameDiv.id = variables[i].variableID + "namearea";
nameDiv.className = "nameDiv";
nameDiv.onclick = (function (varid) {
return function () { showvariable(varid); };
})(variables[i].variableID);
nameDiv.appendChild(document.createTextNode(variables[i].name));
namearea.appendChild(nameDiv);
var descriptionDiv = document.createElement('div');
descriptionDiv.id = variables[i].variableID + "description";
descriptionDiv.className = "descriptionDiv";
descriptionDiv.appendChild(document.createTextNode("Description : " + variables[i].description));
description.appendChild(descriptionDiv);
var varidDiv = document.createElement('div');
varidDiv.id = variables[i].variableID + "varid";
varidDiv.className = "varidDiv";
varidDiv.appendChild(document.createTextNode("Var ID : " + variables[i].variableID));
varid.appendChild(varidDiv);
var initialvalueDiv = document.createElement('div'); ;
initialvalueDiv.id = variables[i].variableID + "initialvalue";
initialvalueDiv.className = "initialvalueDiv";
initialvalueDiv.appendChild(document.createTextNode("Initial Value : " + variables[i].value));
initialvalue.appendChild(initialvalueDiv);
var valuelockDiv = document.createElement('div');
valuelockDiv.id = variables[i].variableID + "valuelock";
valuelockDiv.className = "valuelockDiv ";
valuelockDiv.appendChild(document.createTextNode("Value : " + variables[i].value));
valuelockDiv.appendChild(document.createTextNode("Lock : " + variables[i].locked.toString()));
valuelock.appendChild(valuelockDiv);
variableIDArray[variables[i].variableID];
}
};
function showvariable(varid) {
for (v in variableIDArray)
hide(variableIDArray[v]);
show(varid + "description");
show(varid + "varid");
show(varid + "initialvalue");
show(varid + "valuelock");
}
function show(elemid) {
document.getElementById(elemid).style.display = "block";
}
function hide(elemid) {
document.getElementById(elemid).style.display = "none";
}
Yes. jQuery. Will reduce your code to about 6 lines. :) http://jquery.com

JavaScript "null or not an object" error

I'm running the JavaScript below to place horizontal scrolling text on the banner of my website. It works in one server but not another. I get the following error:
Error: 'this.mqo' is null or not an object
JavaScript:
function start() {
new mq('m1');
/* new mq('m2');
*/
mqRotate(mqr); // must come last
}
window.onload = start;
// Continuous Text Marquee
// permission to use this Javascript on your web page is granted
// provided that all of the code below in this script (including these
// comments) is used without any alteration
function objWidth(obj) {
if (obj.offsetWidth) return obj.offsetWidth;
if (obj.clip) return obj.clip.width;
return 0;
}
var mqr = [];
function mq(id) {
this.mqo = document.getElementById(id);
var wid = objWidth(this.mqo.getElementsByTagName('span')[0]) + 5;
var fulwid = objWidth(this.mqo);
var txt = this.mqo.getElementsByTagName('span')[0].innerHTML;
this.mqo.innerHTML = '';
var heit = this.mqo.style.height;
this.mqo.onmouseout = function () {
mqRotate(mqr);
};
this.mqo.onmouseover = function () {
clearTimeout(mqr[0].TO);
};
this.mqo.ary = [];
var maxw = Math.ceil(fulwid / wid) + 1;
for (var i = 0; i < maxw; i++) {
this.mqo.ary[i] = document.createElement('div');
this.mqo.ary[i].innerHTML = txt;
this.mqo.ary[i].style.position = 'absolute';
this.mqo.ary[i].style.left = (wid * i) + 'px';
this.mqo.ary[i].style.width = wid + 'px';
this.mqo.ary[i].style.height = heit;
this.mqo.appendChild(this.mqo.ary[i]);
}
mqr.push(this.mqo);
}
function mqRotate(mqr) {
if (!mqr) return;
for (var j = mqr.length - 1; j > -1; j--) {
maxa = mqr[j].ary.length;
for (var i = 0; i < maxa; i++) {
var x = mqr[j].ary[i].style;
x.left = (parseInt(x.left, 10) - 1) + 'px';
}
var y = mqr[j].ary[0].style;
if (parseInt(y.left, 10) + parseInt(y.width, 10) < 0) {
var z = mqr[j].ary.shift();
z.style.left = (parseInt(z.style.left) + parseInt(z.style.width) * maxa) + 'px';
mqr[j].ary.push(z);
}
}
mqr[0].TO = setTimeout('mqRotate(mqr)', 10);
}
The reason is most likely that there is no element with the id "m1". Place this line first in the start function to diagnose this:
alert(document.getElementById('m1'));
If it shows "[Object]" (or similar), the element exists and it's some other problem, but if it shows "undefined" it means that there is no such element in the page.

Categories