How to set a global variable in JavaScript? - javascript

I want to increment a counter each time I call a function.
But it is being set to 0 each time I call it.
How can I maintain the updated value of nextKeyIndex?
I am calling getKey function from a javascript file.
Other javascript file which should return updated index (from 0 to 4) has below code..
var nextKeyIndex=0;
function getKey() {
if (nextKeyIndex == 4)
nextKeyIndex = 0;
else
nextKeyIndex = nextKeyIndex + 1;
alert(nextKeyIndex);

I tried you code as below and its working for me. Please try below code.
<script>
var nextKeyIndex=0;
function getKey() {
if (nextKeyIndex == 4)
nextKeyIndex = 0;
else
nextKeyIndex = nextKeyIndex + 1;
alert(nextKeyIndex);
}
</script>
<input type="button" onclick="getKey()" value="click" />

All variables in javascript are by default global if you do not explicitly declare them within a function. Are you sure that the first line declaration (var nextKeyIndex=0) is not being re-run or reloaded somewhere?
Click Me To Increment
var nextKeyIndex=0;
getKey=function() {
if (nextKeyIndex == 4)
nextKeyIndex = 0;
else
nextKeyIndex = nextKeyIndex + 1;
alert(nextKeyIndex);
}
It works for me in jsfiddle:
http://jsfiddle.net/WJYx2/

How to set a global variable in javascript?
You can set a global variable if you declare something without var or declare it as part of window object
global = 10; // global variable
window.global = 10; // also global variable

var nextKeyIndex=0;
function getKey() {
if (nextKeyIndex == 4){
nextKeyIndex = 0;
}else{
nextKeyIndex = nextKeyIndex + 1;
}
alert(nextKeyIndex);
}

Related

Is these a way to add 1 and then after one second than add 2 and than 3 etc

What I am looking for would essentially be a "++" to a "++" command using native java script. The program simply runs an animation for a given number in which the idea of the animatio is that it adds 1 after one second, two after two seconds and keeps going in the same fashion until the animation is stopped.
var counter = 10;
var animationOn = false;
var counterAnimation;
var plusOne;
function updateCounter() {
//update the counter value
var plusOne = counter++;
for (var i = 1; i = < 100000000;) {
}
//show the counter
var counterSpan = document.getElementById("counterHolder");
counterSpan.innerHTML = plusOne;
}
function startCounterAnimation() {
if (animationOn == false) {
animationOn == true;
counterAnimation = setInterval(updateCounter, 1000);
}
}
function stopCounterAnimation() {
if (animationOn == true) {
animationOn == false;
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="startCounterAnimation();">
Start counter animation
</button>
<button onclick="stopCounterAnimation();">
Stop counter animation
</button>
<span id="counterHolder">6931418</span>
</body>
</html>
You don't need the for loop.
You should assign to the global plusOne variable, not declare a local variable in the function.
You should add counter++ to it, not assign that directly.
Initialize plusOne from the number already in the output span.
Since your time intervals change between each update, you can't use setInterval(). Use setTimeout() to make a different timeout each time.
Use =, not ==, to assign to the animationOn variable.
var counter;
var animationOn = false;
var counterAnimation;
var plusOne = parseInt(document.getElementById("counterHolder").innerHTML);
function updateCounter() {
//update the counter value
plusOne += counter++;
//show the counter
var counterSpan = document.getElementById("counterHolder");
counterSpan.innerHTML = plusOne;
counterAnimation = setTimeout(updateCounter, counter * 1000);
}
function startCounterAnimation() {
if (!animationOn) {
animationOn = true;
counter = 1;
counterAnimation = setTimeout(updateCounter, 1000 * counter);
}
}
function stopCounterAnimation() {
if (animationOn) {
animationOn = false;
clearTimeout(counterAnimation);
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="startCounterAnimation();">
Start counter animation
</button>
<button onclick="stopCounterAnimation();">
Stop counter animation
</button>
<span id="counterHolder">6931418</span>
</body>
</html>
You canĀ“t define var onePlus in two places, instead define it once and assign a value, var is wide scoped
Also add whatever logic you need in the for loop and put the onePlus ++ and counter as parts of the for loop
As it is now you are expecting to use the counter both outside the for loop and as the for loop middle part, which seems reduntant
Try something like(leaving the variable names as are):
var counter = 1000
for (var plusOne = 1; plusOne < counter; plusOne++) {
//Your logic in here
await sleep(1000);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

SetInterval running even after i clear it

Im having a little trouble fixing a problem i have with setInterval.
I have a function that runs when i click an element on my website that sets var pass = 1;
if you look in color1(); there is a set Interval that clears itself when pass > 0; so if pass = 1; then it should clear itself, it does, but only after running the interval one more time.
so it - runs setInterval, clears setInterval, then runs the rest of the code in setInterval. What i need, is for setInterval to clear without running the code again.
Thanks in advance
function color1() {
var pass = 1;
var counter = 2;
var animationSpeed = 800;
var $colorContent = '.color-container-1 .color-content-container'
var colorInterval = setInterval(function() {
if (pass > 0) {
clearInterval(colorInterval);
}
$($colorContent).fadeOut(0);
$(($colorContent + '-' + counter)).fadeIn(animationSpeed);
++counter
if (counter === $($colorContent).length + 1) {
counter = 1;
}
}, 3000);
}
It should be like below, you should return the function. Here you have cleared the interval but you haven't stopped the execution
var colorInterval = setInterval(function() {
if (pass > 0) {
clearInterval(colorInterval);
return; //stop here so that it doesn't continue to execute below code
}
$($colorContent).fadeOut(0);
$(($colorContent + '-' + counter)).fadeIn(animationSpeed);
++counter
if (counter === $($colorContent).length + 1) {
counter = 1;
}
}, 3000);

clearInterval() not working

SYNTAX ERRORS FIXED. Dreamweaver says that I have an error in my code on line 52. I can't see what is wrong? Maybe this has something to do with the fact that my if and else statements are not working.
IF AND ELSE STATEMENTS FIXED. If I test the if and else statements individually they work correctly, but when I run the entire document, they do not run. Could someone tell me if the error and my if/else statements not working are related or if there is something else wrong.
<script>
var car1=new Object();
car1.Name="Rusty";
car1.Speed="1px", 40;
car1.Distance=0;
var car2=new Object();
car2.Name="Dusty";
car2.Speed="2px", 40;
car2.Distance=0;
var car3=new Object();
car3.Name="Crankshaft";
car3.Speed="4px", 40;
car3.Distance=0;
function runRusty(){
setInterval(function(){moveRusty()},40);
function moveRusty(){car1.Distance=car1.Distance +1
document.getElementById("rusty").style.marginLeft=car1.Distance + "px"
};
};
function runDusty(){
setInterval(function(){moveDusty()},40);
function moveDusty(){car2.Distance=car2.Distance +1
document.getElementById("dusty").style.marginLeft=car2.Distance + "px"
};
};
function runCrankshaft(){
setInterval(function(){moveCrank()},40);
function moveCrank(){car3.Distance=car3.Distance +1
document.getElementById("crankshaft").style.marginLeft=car3.Distance + "px"
};
};
function winLose () {if (document.getElementById("rusty").style.marginLeft="900px"){
alert("Winner is Rusty!");
clearInterval(runRusty);
}
else if(document.getElementById("dusty").style.marginLeft="900px"){
alert("Winner is Dusty!");
clearInterval(runDusty);
}
else if(document.getElementById("crankshaft").style.marginLeft="900px"){
alert("Winner is Crankshaft!");
clearInterval(runCrankshaft);
};
};
</script>
EDIT:
The if and else statements now work as I changed declared my functions globally and changed them slightly. The code now looks as such:
var car1=new Object();
car1.Name="Rusty";
car1.Speed=1;
car1.Distance=0;
var car2=new Object();
car2.Name="Dusty";
car2.Speed=2;
car2.Distance=0;
var car3=new Object();
car3.Name="Crankshaft";
car3.Speed=4;
car3.Distance=0;
var moveRusty;
var moveDusty;
var moveCrankShaft;
function runRusty(){
moveRusty=setInterval(function(){
car1.Distance=car1.Distance + car1.Speed;
document.getElementById("rusty").style.marginLeft=car1.Distance + "px";
winLose();
},40);
};
function runDusty(){
moveDusty=setInterval(function(){
car2.Distance=car2.Distance + car2.Speed;
document.getElementById("dusty").style.marginLeft=car2.Distance + "px";
winLose();
},40);
};
function runCrankshaft(){
moveCrankShaft=setInterval(function(){
car3.Distance=car3.Distance + car3.Speed;
document.getElementById("crankshaft").style.marginLeft=car3.Distance + "px";
winLose();
},40);
}
function winLose () {
if (car1.Distance >= 900){
alert("Winner is Rusty!");
car1.Distance = 0;
car1.Speed = 0;
car2.Distance = 0;
car2.Speed = 0;
car3.Distance = 0;
car3.Speed = 0;
}
else
if(car2.Distance >= 900){
alert("Winner is Dusty!");
car1.Distance = 0;
car1.Speed = 0;
car2.Distance = 0;
car2.Speed = 0;
car3.Distance = 0;
car3.Speed = 0;
}
else
if(car3.Distance >= 900){
alert("Winner is Crankshaft!");
car1.Distance = 0;
car1.Speed = 0;
car2.Distance = 0;
car2.Speed = 0;
car3.Distance = 0;
car3.Speed = 0;
}
};
clearInterval(moveRusty);
clearInterval(moveDusty);
clearInterval(moveCrankShaft);
Everything works now. All the alerts happen and the position of the cars is reset. But all my clearInterval() do not work. I don't know if clearInterval() is the correct thing to use. What I want to do is reset the page so that I can run the "game" again. Right now, the only way to do that is by refreshing the page. I've double checked how I've declared my setInterval() and how I'm calling them in my clearInterval(), and as far as I can it's right?
You are using clearInterval() wrong. You are passing it a function parameter whereas it expects an object.
// correct usage
var time = setInterval(stuff, 100);
clearInterval(time);
You have a semi colon before the else. ; which is a syntax error, remove it . You have a lot of them in weird places also, I suggest you don't put them after function declarations, if blocks if/else blocks, loop blocks etc.
When you want to test if to things are 'equal' in a if statement, you need to use == or === and NOT =
if (document.getElementById("crankshaft").style.marginLeft = "900px") // WRONG
if (document.getElementById("crankshaft").style.marginLeft == "900px") // RIGHT
if (document.getElementById("crankshaft").style.marginLeft === "900px") // BETTER
Read the answer to the following question to know the difference between == and ===
Difference between == and === in JavaScript
Hope this helps

some errors with javascript objects

I am beginning to hate objects in javascript.
Every time I have error and I fix it, a new error appears, and so on.
Can you please take a look at the following code and tell me what's wrong ?
problem message:
"this.Images is undefined"
and more errors also
HTML File
<div id="SlideShow" >
<img id="img" src="images/img.jpg" alt="" /><span id="desc"></span>
</div>
<script type="text/javascript">
meToo.Images = ['images/img.jpg','images/img2.jpg','images/img3.jpg','images/img4.jpg','images/img5.jpg'];
meToo.Titles = ['Pic1','pic2','Pic3','Pic4','Pic5'];
meToo.Play('img');
</script>
Javascript Object
var meToo = {
Images: [],
Titles: [],
counter: 0,
Play: function(ElemID){
var element = document.getElementById(ElemID);
var ImgLen = this.Images.length;
if(this.counter < ImgLen){
this.counter++;
element.src = this.Images[this.counter];
element.nextSibling.innerHTML = this.Titles[this.counter];
}else{
this.counter = 0;
}
setTimeout(this.Play, 1000);
}
};
See the Example
See this question. Otherwise setTimeout sets this to the window object. Also, the counter should be incremented after setting the images or you will be reading outside the array bounds.
Finally, when resetting the counter to 0, there will be an additional one-second delay before the loop restarts, because the image is not being reset in that else block. You may wish to rewrite that part of the logic.
Updated Fiddle
if(this.counter < ImgLen){
element.src = this.Images[this.counter];
element.nextSibling.innerHTML = this.Titles[this.counter];
this.counter++;
}else{
this.counter = 0;
}
var _this = this;
setTimeout(function() { _this.Play('img') }, 1000);
This is what I would write to keep the loop going at one-second intervals:
Play: function(ElemID) {
var element = document.getElementById(ElemID);
var ImgLen = this.Images.length;
if (this.counter == ImgLen) {
this.counter = 0;
}
element.src = this.Images[this.counter];
element.nextSibling.innerHTML = this.Titles[this.counter];
this.counter++;
var _this = this;
setTimeout(function() {
_this.Play('img')
}, 1000);
}
if(this.counter < ImgLen)
is wrong.
What will happen here is that when you run
this.counter++;
the value of that variable will now be ImgLen.length
Arrays in javascript go from 0 to length -1.So now you'll be exceeding the array's length, when you run:
this.Images[this.counter];
and encounter an error.
The quick fix here is to change to
if(this.counter < ImgLen -1)
If you're encountering other problems, then post the exact error message. (Run in Chrome and press F12 (for example) to bring up the console so you can see the errors).
Here check this out.It should work perfectly for you.I have made it a singleton object and also I am doing a check if incase meToo.Play is called before the dom is loaded it will not crash.All the other mistakes that the guys above are pointing are also taken care of.
<script>
var meToo = function(){
var Images = ['http://www.image-upload.net/di/WMPI/img.jpg','http://www.image-upload.net/di/HPUQ/img2.jpg','http://www.image-upload.net/di/WQ9J/img3.jpg','http://www.image-upload.net/di/GIM6/img4.jpg','http://www.image-upload.net/di/0738/img5.jpg'];
var Titles = ['Pic1','pic2','Pic3','Pic4','Pic5'];
var counter = 0;
return {
Play: function(ElemID) {
var element = document.getElementById(ElemID);
if(element){
var ImgLen = Images.length;
if(counter < ImgLen) {
element.src = Images[counter];
element.nextSibling.innerHTML = Titles[this.counter];
counter++;
} else {
counter = 0;
}
}
setTimeout(callmeToo, 1000);
}
}
}();
function callmeToo(){
meToo.Play('img');
}
callmeToo();
</script>

javascript array cycling only first var

I am using javascript to cycle through an array of urls within an iframe and so far when the prev or next buttons are pressed it jumps to the first var in the array and both prev and next functions end. Any ideas?
<iframe id="myFrame" src="http://startpage.com" width="484px" height = "424px"></iframe>
<button onclick = "prevPage(); ">Prev</button>
<button onclick = "nextPage(); ">Next</button>
<script>
var sites=new Array();
sites[0]="http://site1.html";
sites[1]="http://site2.html";
sites[2]="http://site3.html";
sites[3]="http://site4.html";
function nextPage() {
var number = document.getElementById("myFrame").src;
number = number.substring(number.length - 4 ,number.length-3);
number = parseInt(number) + 1;
document.getElementById("myFrame").src=sites[0];
}
function prevPage() {
var number = document.getElementById("myFrame").src;
number = number.substring(number.length - 3 ,number.length-4);
number = parseInt(number) - 1;
document.getElementById("myFrame").src=sites[0];
}
</script>
Why are you using the URL as your 'position' storage? It'd be FAR easier to just use a variable:
var curPos = 0;
function nextPage() {
curPos++;
if (curPos >= sites.length) {
curPos = 0;
}
document.getElementById('myframe').src = sites[curPos];
}
function prevPage() {
curPos--;
if (curPos < 0) {
curPos = sites.length - 1;
}
document.getElementById('myframe'.).src = sites[curPos];
}
If I understood your problem correctly I think all you need to do is use document.getElementById("myFrame").src=sites[number]; instead of document.getElementById("myFrame").src=sites[0];
May be
document.getElementById("myFrame").src=sites[number-1];
is what you are trying to do in both functions.

Categories