Javascript executes both if and else - javascript

Here's my code:
var srcArray = ["_images/overlook.jpg","_images/winery_sign.jpg","_images/lunch.jpg","_images/bigSur.jpg","_images/flag_photo.jpg","_images/mission_look.jpg"];
var myImg = document.getElementById("mainImage");
var imgIndex = 0;
var status = false;
myImg.onclick = function () {
if (status) {
var collage = setInterval(changeSrc,1500);
status = true;
} else {
clearInterval(collage);
status = false;
}
}
function changeSrc (){
myImg.setAttribute("src",srcArray[imgIndex]);
imgIndex++;
if (imgIndex == srcArray.length) {
imgIndex = 0;
}
}
What I'm trying to do is to set interval on changeSrc when interval is not set and clear interval when interval is set. I saw in Firebug that browser executes first part of if and then executes second line of else (status = false).
Once interval is set when I click on image it starts another interval on the same image. It basically just runs faster with every click and doesn't stop.
Where's the problem?
Thanks in advance for your help :)

Do this:
myImg.onclick = function () {
if (status) {
var collage = setInterval(changeSrc,1500);
} else {
clearInterval(collage);
}
status = !status;
}
In your code, you are initializing status incorrectly

Just move collage var out of if statement because when you declare it into if statement this variable only will exist in this scope.
And I don't know why it don't work with bool that's why I change it to number :P I hope someone else can answer that.
var myImg = document.getElementById("mainImage");
var imgIndex = 0;
var status = 1;
var collage;
myImg.onclick = function ()
{
if(status == 1)
{
collage = setInterval(changeSrc,1500);
status = 0;
}
else
{
clearInterval(collage);
status = 1;
}
}

When you click the image it starts the images rolling over, instant for first, than per timer if you click it stops. I assume that is the desired effect. You don't need the status.
var srcArray = ["_images/overlook.jpg","_images/winery_sign.jpg","_images/lunch.jpg","_images/bigSur.jpg","_images/flag_photo.jpg","_images/mission_look.jpg"],
myImg = document.getElementById("mainImage"),
imgIndex = 0,
tmr;
myImg.onclick = function () {
// if tmr === undefined, start the rollover.
if (!tmr) {
// I call changeSrc() to give instant feedback on first click!
changeSrc();
tmr = setInterval(changeSrc,1500);
// else if tmr has a value stop the rollover, make sure we set tmr to undefined.
}else{
clearInterval(tmr);
tmr=undefined; !IMPORTANT
}
}
function changeSrc (){
myImg.setAttribute("src",srcArray[imgIndex]);
imgIndex++;
if (imgIndex == srcArray.length) {
imgIndex = 0;
}
}
http://jsfiddle.net/uq8mfLun/2/

Change the status in function changeSrc() instead of doing it in if else.

Your code works pretty well. You have to change:
if (status)
by
if (status == true)
also
if (status === true)
Explanation: If you write if(status === true), the result will be true only if status is true. But if you write if(status), the result will be true for any status that is different from false, null, empty string, undefined value, or 0.
Hope it useful!

Related

Why is this function youWin not working properly?

I believe I'm posting all of the relevant code here.
The function definitely does run because if I switch the > to a < it gives me the alert when I click on the 'moveup' button.
Also, the console logs that pic2 continues to grow with each increment and pic3 stays the same. So that part is working.
Something in the function just isn't comparing the two variables properly and I can't figure out what's wrong.
var player = document.getElementById("pic2").offsetLeft;
var finish = document.getElementById("pic3").offsetLeft;
console.log(player);
console.log(finish);
function youWin() {
if (player >= finish) {
alert("You Win!");
} else {
}
};
$(function() {
$('#moveup').click(function() {
$("#pic2").css('margin-left', '+=2vw');
$("#pic3").css('margin-left', '-=2vw');
document.getElementById("guessField").value = "";
$('#myModalTrue').toggle();
y = regenerate();
var player = document.getElementById("pic2").offsetLeft;
var finish = document.getElementById("pic3").offsetLeft;
console.log(player);
console.log(finish);
youWin();
});
});
you aren't changing the global player and finish variable. you are making new local ones. for more information about variable scope in javascript. try this
var player = document.getElementById("pic2").offsetLeft;
var finish = document.getElementById("pic3").offsetLeft;
console.log(player);
console.log(finish);
function youWin() {
if (player >= finish) {
alert("You Win!");
} else {
}
};
$(function() {
$('#moveup').click(function() {
$("#pic2").css('margin-left', '+=2vw');
$("#pic3").css('margin-left', '-=2vw');
document.getElementById("guessField").value = "";
$('#myModalTrue').toggle();
y = regenerate();
player = document.getElementById("pic2").offsetLeft;//change is here
finish = document.getElementById("pic3").offsetLeft;//and here
console.log(player);
console.log(finish);
youWin();
});
});
Try logging values inside the youWin function it should return old values and your answer. Your player and finish values are not updating for function. It is still getting old values.
function youWin(player, finish) {
if (player >= finish) {
alert("You Win!");
} else {
}
};
$(function() {
$('#moveup').click(function() {
$("#pic2").css('margin-left', '+=2vw');
$("#pic3").css('margin-left', '-=2vw');
document.getElementById("guessField").value = "";
$('#myModalTrue').toggle();
y = regenerate();
var player = document.getElementById("pic2").offsetLeft;
var finish = document.getElementById("pic3").offsetLeft;
console.log(player);
console.log(finish);
youWin(player, finish);
});
});

My tic tac toe game (jquery) is not working properly. Lost Part is not working properly

The 'Win' and 'Draw' parts are showing up on time, but the 'Lost' part doesn't show the message 'you lost'until I click on an empty cell once again. Please check out my code and help me find any errors.
Below is my code:
Marked is a class that changes the opacity of the clicked cell.
1,2,3...are the id's of respective cells in the table(html).
I tried delay() too instead of setTimeout(), but it didn't work as well.
$(document).ready(function() {
var timer;
var x = 0;
$("td").click(function() {
if($(this).text()=='') {
$(this).text("0").addClass("marked");
x = 1;
}
}).click(function() {
if(x==1) {
timer = setTimeout(function() {
var choose = $("td").not(".marked");
var random = choose[Math.floor(Math.random()*choose.length)];
$(random).text("X").addClass("marked");
},1000);
x=0;
showResult();
}
});
function showResult() {
var one = $("#1").text();
var two = $("#2").text();
var three = $("#3").text();
var four = $("#4").text();
var five = $("#5").text();
var six = $("#6").text();
var seven = $("#7").text();
var eight = $("#8").text();
var nine = $("#9").text();
if(one==two && two==three)
result(one)
else if (four==five && five==six)
result(four)
else if(seven==eight && eight==nine)
result(seven)
else if (one==four && four==seven)
result(one)
else if (two==five && five==eight)
result(two)
else if (three==six && six==nine)
result(three)
else if (one==five && five==nine)
result(one)
else if(three==five && five==seven)
result(three);
else {
var z = $("td").not(".marked");
if(z.length == 0) {
$("p").text("Draw!");
$("td").removeClass("marked");
$("td").text("");
$("#demo1").append('<img src="https://media.tenor.com/images/54c63f726505bfdb455eb4c29e626ad8/tenor.gif">');
clearTimeout(timer);
}
}
}
function result(y) {
var result = y;
if(result=="X"){
clearTimeout(timer);
$("p").text("You Lost!");
$("td").removeClass("marked");
$("td").text("");
$("#demo1").append('<img src="https://media.tenor.com/images/08902a85a6107684f8614846f4a54218/tenor.gif">');
}
if(result=="0") {
$("td").text("");
$("p").text("You Won!");
$("#demo1").append('<img src="https://i.gifer.com/4OuC.gif">');
$("td").removeClass("marked");
clearTimeout(timer);
}
}
});
You are calling showResult immeadiately when the user clicked, so it cant't recognize the X put into the table one second later.
Just do:
$("td").click(function() {
[...]
}).click(function() {
if (x == 1) {
timer = setTimeout(function() {
var choose = $("td").not(".marked");
var random = choose[Math.floor(Math.random() * choose.length)];
$(random).text("X").addClass("marked");
/******** ADD ANOTHER CHECK HERE ********/
showResult();
}, 1000);
x = 0;
showResult();
}
});
It might also be a good idea to add a return to showResult that returns false when a result was achieved. This way you could do something like
x = 0;
if (showResult()) {
timer = setTimeout(function() {
[...]
}
}
And the user can't get a loose message right after a win message.
Also: Why do you need the 2 click listeners? You can just use the if statement in the top one and then you don't need the (x == 1)

Stopping a function from running

I have 3 sequential divs to display on a page, the page loads showing div 1, by going onto the 2nd it starts a timer, when that timer runs out it goes back to the first div. Navigating through to the next div should start the timer again. The timer function works OK on the first page but on the second page when it is called it is already running from the previous div and therefore ticks the time down twice as fast, and on the last div 3 times.
How can I get it to stop the currently running function then restart it?
Thanks,
$scope.timeLeft = 0;
var timeoutRunner = function (timerLength) {
$scope.timeLeft = timerLength;
var run = function () {
if ($scope.timeLeft >= 1) {
console.log($scope.timeLeft);
$scope.timeLeft--
$timeout(run, 1000);
} else if ($scope.timeLeft == 0){
$scope.endTransaction();
}
}
run();
}
timeoutRunner(5);
You need to add some logic that calls $timeout.cancel(timeoutRunner);.
Not sure where you want to cancel your timeout exactly (view change? when you end the transaction?) But here is how you would do it:
$scope.timeLeft = 0;
var timeoutPromise = false;
var timeoutRunner = function (timerLength) {
$scope.timeLeft = timerLength;
var run = function () {
if ($scope.timeLeft >= 1) {
console.log($scope.timeLeft);
$scope.timeLeft--
timeoutPromise = $timeout(run, 1000);
} else if ($scope.timeLeft == 0){
$scope.endTransaction();
$timeout.cancel(timeoutPromise);
}
}
run();
}
timeoutRunner(5);
Each time I called the function it created a new instance of it and I was unable to stop it on demand so I found a way to say which instance I want running:
$scope.timeLeft = 0;
var instanceRunning = 0;
var timeoutRunner = function (timerLength, instance) {
$scope.timeLeft = timerLength;
instanceRunning = instance;
var run = function () {
if (instanceRunning == instance){
if ($scope.timeLeft < 7 && $scope.timeLeft > 0){
$('#timer-container').show();
} else {
$('#timer-container').hide();
}
if ($scope.timeLeft >= 1) {
console.log($scope.timeLeft);
$scope.timeLeft--
$timeout(run, 1000);
} else if ($scope.timeLeft == 0){
$scope.endTransaction();
}
}
}
run();
}
timeoutRunner(20, 1);
timeoutRunner(20, 2);
timeoutRunner(20, 3);

jQuery not responding to timed events

Im having trouble getting my second function to react to the changes the first function brings.
var jumbotron = function(){
var jumbotronCounter = 1
var jumbotronSwitch = function(){
var jumbotronTimer = function(){
jumbotronCounter++
}
jumbotronTimer();
if (jumbotronCounter > 3){
jumbotronCounter = 1
}
console.log(jumbotronCounter);
}
setInterval(jumbotronSwitch,7000);
var jumbotronListener = function(){
if(jumbotronCounter = 1){
console.log('first');
}else if(jumbotronCounter = 2){
console.log('second');
}else if(jumbotronCounter = 3){
console.log('third');
}
};
jumbotronListener();
}
jumbotron();
Id like to use "jumbotronListener" to run some code when "jumbotronCounter" changes
jumbotronListener is indeed only running once. You can, instead, run it every time the interval runs:
var jumbotron = function () {
var jumbotronCounter = 1;
var jumbotronSwitch = function () {
var jumbotronTimer = function () {
jumbotronCounter++;
};
jumbotronTimer();
if (jumbotronCounter > 3) {
jumbotronCounter = 1;
}
// Execute the listener every time the interval runs
jumbotronListener();
console.log(jumbotronCounter);
};
setInterval(jumbotronSwitch, 7000);
// Run for the first time if you wish:
jumbotronListener();
// Set this as function so you can 'use it before declaring it'
function jumbotronListener() {
// You had invalid operators. = assigns and === compares (strictly)
if(jumbotronCounter === 1) {
console.log('first');
} else if(jumbotronCounter === 2) {
console.log('second');
} else if(jumbotronCounter === 3) {
console.log('third');
}
}
};
jumbotron();
You also had some missing semicolons in there, sometimes it's not a problem since JavaScript auto-inserts them, but sometimes it is, so it's a good idea to always make sure to manually insert them where they go.

unbind/turn off a function in jquery

Good day all, I'm trying to make a jquery game where a group of enemy will spawn after a group of enemy gets destroyed. I'm calling alien_cruiser() function & unbinding minion_roulette() function after minion_roulette_counter gets 0. But every time I run, function does not get unbind & after counter gets 0 both type of enemies show. I want to run them one by one. Here are the codes:
var sound = new Audio("sounds//dishoom.ogg");
var score = 0;
var minion_roulette_life = 10;
var cruiser_life = 20;
var minion_roulette_counter = 3;
var cruiser_counter = 3;
function processBullet() {
$(".projectile").each(function() {
var maxTop = $(this).offset().top;
var breakable1 = $(this).collision("#minion-roulette");
var breakable2 = $(this).collision("#cruiser");
$(this).css("top", maxTop - 25);
if (breakable1.length != 0 || breakable2.length != 0) {
$(this).remove();
}
if (maxTop <= 35) {
$(this).remove();
}
if (breakable1.length != 0) {
--minion_roulette_life;
if (minion_roulette_life == 0) {
sound.play();
breakable1.remove();
minion_roulette(true);
minion_roulette_counter--;
$("#score").html(++score);
minion_roulette_life = 10;
}
}
//This is the place where it checks if counter is 0 or not
if (minion_roulette_counter == 0) {
$('#content').unbind(function() {
minion_roulette(false)
});
alien_cruiser(false);
minion_roulette_counter = -1;
}
if (breakable2.length != 0) {
--cruiser_life;
if (cruiser_life == 0) {
sound.play();
breakable2.remove();
alien_cruiser(true);
$("#score").html(++score);
cruiser_life = 20;
}
}
});
}
Am I doing any wrong here? Please I need a solution badly. Tnx.
In this situation, you could use a conditional statement to determine which function to call.
For example:
if (minion_roulette_counter == 0) {
alien_cruiser();
}
else {
minion_roulette();
}
Binding and unbinding doesn't 'turn off' a function, unfortunately. To quote MDN:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
– MDN: 'Bind'

Categories

Resources