I'm trying to get something to run after a function using setInterval is done. I'm trying to do this with callbacks but I can't seem to get it work?
So far I have the following
var testing = ['A','D','F','H','B'];
var index = 0;
var wordCount = 1;
var showHide = setInterval(function () {
var displayWords = "";
var mx = index + wordCount;
if (mx > testing.length) mx = testing.length;
for (var i = index; i < mx; i++) {
displayWords += testing[i] + " ";
}
d3.select("#stim").text(displayWords).style("font-size","150px");
index = mx;
if (index > testing.length) {
clearInterval(showHide);
d3.select("#stim").text('L,R').style("font-size","150px");
}
}, 1000);
And I want the following line to execute "after":
d3.select("#stim").text('L,R').style("font-size","150px");
I tried using this method but when I try to put "showHide" in its own function, it doesn't seem to work at all.
Related
I have code that works well when used outside a function. But not sure what goes wrong when I just wrap a function around it.
This is my working code: Idea is to move the pencil in a square path. In the working code, it follows the square path but when I wrap around the function, it keeps going on in a straight line.
var direction ='right';
var angle = 0;
var sum_angle = 0;
for (var count = 0; count < 5; count++) {
if(--window.LoopTrap == 0) throw "Infinite loop.";
move_draw_Player(direction, 100);
var new_angle=90;
$('#player').animate({rotate: '90deg'}, 100);
var angle=angle +new_angle;
sum_angle =sum_angle + angle;
}
function move_draw_Player(directionStr, amount) {
directionStr =angle;
var x = Math.sin(angle*Math.PI/-180) * amount;
var y = Math.cos(angle*Math.PI/-180) * amount;
z= amount/100;
$('#pencil').animate({'left': '-='+x+'px', 'top': '-='+y+'px'}, z*350, 'linear', function() {
//window.counter = window.counter +2;
pen.moveTo((pencil.offset().left - cw.offset().left),(pencil.offset().top+ pencil.height() -ac.offset().top));
});
But when I wrap a function around it, it doesn't work. What could be going wrong?
var direction ='right';
var angle = 0;
var sum_angle = 0;
function Draw_Square() {
for (var count = 0; count < 5; count++) {
if(--window.LoopTrap == 0) throw "Infinite loop.";
move_draw_Player(direction, 100);
var new_angle=90;
$('#player').animate({rotate: '90deg'}, 100);
var angle=angle +new_angle;
sum_angle =sum_angle + angle;
}
}
function move_draw_Player(directionStr, amount) {
directionStr =angle;
var x = Math.sin(angle*Math.PI/-180) * amount;
var y = Math.cos(angle*Math.PI/-180) * amount;
z= amount/100;
$('#pencil').animate({'left': '-='+x+'px', 'top': '-='+y+'px'}, z*350, 'linear', function() {
//window.counter = window.counter +2;
pen.moveTo((pencil.offset().left - cw.offset().left),(pencil.offset().top+ pencil.height() -ac.offset().top));
});
}
//}
Draw_Square();
I have no clue why.
I have checkt everything but it should work.
This shuld be a slidshow for a webseit
<script src="JS/javascript.js">
"use strict";
var image = ['"bilder/1.png"','"bilder/2.png"'];
var i = 0;
aengereHintergrund();
function aengereHintergrund() {
document.getElementById('hintergund').style.backgroundImage = 'url('+image[i]+')';
if(i < image.length){
i ++
}
else {
i = 0
}
setTimeout(aengereHintergrund(),3000);
}
</script>
Oh, the classic function reference vs invocation problem.
Here's what you wrote:
setTimeout(aengereHintergrund(),3000);
And here's what you should have written:
setTimeout(aengereHintergrund,3000);
In the second case, we're passing the function aengereHintergrund itself to setTimeout, which is what we want. In the first case, you're invoking aengereHintergrund, and passing its result (which is nothing, aka undefined) to setTimeout.
(Note: You should also probably use setInterval instead of setTimeout, so you don't have to invoke it again and again. Also also, instead of branching on i >= image.length you can just use i = (i + 1) % image.length).
If you write if (i < images.length) i++;, i will reach images.length. You can fix this error with i++; if (i >= images.length) i = 0;, or i = (i + 1) % images.length; :
var slides = document.getElementById("slides");
var images = ["v67W6.jpg", "USehe.jpg"];
var path = "https://i.stack.imgur.com/";
var i = 0;
nextSlide();
function nextSlide () {
var bg = "url(" + path + images[i] + ")";
slides.style.backgroundImage = bg;
i = (i + 1) % images.length;
setTimeout(nextSlide, 1000);
};
<img id="slides" width="300" height="100" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">
So, I have a code here that works perfectly fine when I am viewing it in the active browser tab. But, as soon as I minimize or switch between other tabs of the browser (which is chrome by the way) the code starts giving issues. Here is the code below:
var a = document.getElementById("slidermain");
var b = a.getElementsByTagName("IMG");
var len = b.length;
var noOpac = 0;
var fullOpac = 10;
var imgNumb = 0;
function initFade(count){
imgNumb = imgNumb + count;
if(imgNumb < 0){
imgNumb = len;
}
if(imgNumb > len){
imgNumb = 1;
}
elem = b[imgNumb-1];
startFadeEffect(elem);
}
function startFadeEffect(elem){
var opacSetting = noOpac / 10;
if(noOpac > 10){
opacSetting = 1;
}
elem.style.opacity = opacSetting;
elem.style.display = "block";
noOpac++;
var timer = setTimeout(function() { startFadeEffect(elem); }, 55);
if(opacSetting == 1){
clearTimeout(timer);
elem.style.opacity = 1;
noOpac = 0;
setTimeout(function() { endFadeEffect(elem); }, 2000);
}
}
function endFadeEffect(elem){
var opacSetting = fullOpac / 10;
if(fullOpac < 0){
opacSetting = 0;
}
elem.style.opacity = opacSetting;
fullOpac--;
var timer = setTimeout(function() { endFadeEffect(elem); }, 55);
if(opacSetting == 0){
clearTimeout(timer);
elem.style.opacity = 0;
elem.style.display = "none";
fullOpac = 10;
return false;
}
}
function autoFade(){
var loop = setInterval("initFade(1)", 4000);
}
Please not that I have been looking on this site for the answer, but mostly the ones I have found are JQuery based solutions; however, I am looking for a JavaScript only solution in which I might not have to use the get new date function. Please do not mark my question as duplicate as I have done good research. Thanks!
This is not a problem with your javascript, but with Chrome. Chrome does some weird things with your tabs when they aren't active. Add code to "fix the mess", or account for not the tab being active, to recover after tabbing out and back in.
I am building a very simple memory game for a small project. The logic is as follows:
click on the input field to choose with how many pairs would you like to play
create divs with classes card1, card2 etc.
clone divs and randomize their place in the array
Here is my script (fork in JSFiddle):
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>") &&
$(".card" + i).clone().appendTo(".container");
}
// randomize cards in stack
var cards = $(".cards");
for (var i = 0; i < cards.length; i++) {
var target = Math.floor(Math.random() * cards.length - 1) + 1;
var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
var target3 = Math.floor(Math.random() * cards.length - 1) + 1;
cards.eq(target).before(cards.eq(target2)).before(cards.eq(target3));
}
});
what I need now is to adjust the 3rd step, meaning to dynamically create the target vars, and the last line of the code
cards.eq(target).before(cards.eq(target2)).before(cards.eq(target3));
So please make me a suggestion - how would you do it? And bare in mind this is a project for beginners. Thank you!
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>") &&
$(".card" + i).clone().appendTo(".container");
}
var parent = $(".container");
var divs = parent.children();
while (divs.length) {
parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
}
});
see jsfidle: http://jsfiddle.net/007y4rju/8/
source: http://jsfiddle.net/C6LPY/2/
Here is the version of the code in jsfiddle - http://jsfiddle.net/007y4rju/6/
Please, check if the behavior is consistent with the original code.
$(document).ready(function () {
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>") &&
$(".card" + i).clone().appendTo(".container");
}
// randomize cards in stack
var cards = $(".cards");
var startTarget = Math.floor(Math.random() * cards.length - 1) + 1;
var collection = cards.eq(startTarget);
var nextTarget;
var i;
for (i = 0; i < cards.length; i++) {
nextTarget = Math.floor(Math.random() * cards.length - 1) + 1;
collection.before(cards.eq(nextTarget));
}
});
});
You can randomize index in a class name (card%i%) when cloning divs. Then you don't need to shuffle cloned divs; you can append them as is.
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>");
}
var aIndices = [];
for (var i = 1; i <= numCards; i++) {
var ix;
do ix = Math.round(Math.random() * (numCards - 1)) + 1;
while (aIndices.indexOf(ix) >= 0);
aIndices.push(ix);
// clone
$(".card" + ix).clone().appendTo(".container");
}
});
I'm trying to create a gallery script with JS (I've only been learning for a week so please excuse if I've made any ridiculous mistakes!). When I run the code, I get an error for controlLeft.onclick = changeImage(--);, saying ( is an unexpected token.
By my untrained eye everything should be fine, but evidently not. What have I done wrong here:
//Javascript Image Changer
var currentImage = document.getElementById("currentImage");
var imageArray = ["img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg"];
var imageIndex= 0;
function changeImage(param){
currentImage.setAttribute("src", imageArray[imageIndex]);
imageIndex[param];
if (imageIndex >= imageArray.length){
imageIndex = 0;
}else if(imageIndex <= -1){
imageIndex = imageArray.length + 1;
}
}
var controlLeft = document.getElementById("left");
var controlRight = document.getElementById("right");
controlLeft.onclick = changeImage(--);
controlRight.onclick = changeImage(++);
You can't just pass operators around like other things. Even in a programming language with higher-order functions the same thing usually does not apply to operators.
Besides that, onclick expects a function - not the result of a function call.
Here's a snippet that is likely to work:
function changeImage(mod){
currentImage.setAttribute("src", imageArray[imageIndex]);
imageIndex += mod;
if (imageIndex >= imageArray.length){
imageIndex = 0;
}else if(imageIndex <= -1){
imageIndex = imageArray.length + 1;
}
}
var controlLeft = document.getElementById("left");
var controlRight = document.getElementById("right");
controlLeft.onclick = function() { changeImage(-1); };
controlRight.onclick function() { changeImage(1); };
Just make a slight modification:
controlLeft.onclick = function() {
changeImage('back');
};
controlRight.onclick = function() {
changeImage('forward');
};