I want to get back to the start of the array but it keeps returning the second item in the array.
var counter = 0;
var srcArray = ["/images/e2450-1.png", "/images/e2450-2.png", "/images/e2450-3.png"];
function nextFunction() {
document.getElementById("chat-bubble").src = srcArray[++counter];
if (counter == 2) {
counter = 0;
};
return srcArray;
}
If anybody could help it would be great.
You are incrementing your counter before using it. try counter++.
++counter increment the counter than evaluate the expression.
counter++ evaluate the expression then increment the counter.
var counter = 0;
var srcArray = ["/images/e2450-1.png", "/images/e2450-2.png", "/images/e2450-3.png"];
function nextFunction() {
document.getElementById("chat-bubble").src = srcArray[counter++];
if (counter == 2) {
counter = 0;
}
return srcArray;
}
Array index starts from 0 and not 1. The below change should work
document.getElementById("chat-bubble").src = srcArray[counter++];
This will set srcArray[0] which is the 1st item in array and then increment the count to 1.
Related
I'm trying to write a very simple jQuery function which includes checking for a value of an input field and if that is greater than 0, setting a variable counter as that value. Otherwise use another value. However, no matter the value of the field, another is always set and I don't understand.
Jquery
$('.test').click(function(e) {
var counter = 0;
var fieldvalue = $("#fieldID").val();
if (parseInt(fieldvalue >= 1)) {
counter = fieldvalue;
} else {
counter = 0; // in reality this will be a dynamic value
}
});
The problem is that counter always returns 0.
you mean fieldvalue in if (parseInt(fieldcounter >= 1) and it has wrong parentheses.
$('.test').click(function(e) {
var counter = 0; // in reality this is a dynamic value
var fieldvalue = $("#fieldID").val();
if (parseInt(fieldvalue) >= 1) {
counter = fieldvalue;
}
else {
counter = 0;
}
console.log(counter)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" id="fieldID">
<input type="button" value="fieldID" class="test">
The correct variable seems to be fieldvalue and not fieldcounter. The >= comparison must be done outside the parseInt function. counter must also receive the result of the parseInt funcion, otherwise it could receive a String.
var fieldvalue = parseInt($("#fieldID").val());
if (fieldvalue >= 1) {
counter = fieldvalue;
I have an array which is taking values over the space of a second and calculating the average. The array is then permanently storing the values. I need them to remove the values after the average has been calculated. I have tried clearing the array at the end of the calculateAverage function using levelMeasurements = []; and levelMeasurements = 0; but that does not work.
Any help on this would be greatly appreciated, thanks!
My code:
var levelMeasurements = [];
function collectLevelMeasurements() {
levelMeasurements.push(averagingLevel);
}
var collectInterval = window.setInterval(collectLevelMeasurements, 0);
function calculateAverage() {
window.clearInterval(collectInterval);
var avg = 0;
for (counter = 0; counter < levelMeasurements.length; counter++) {
avg += levelMeasurements[counter] / levelMeasurements.length;
}
averageAbsoluteLevel = Math.abs(avg);
averageDbLevel = Tone.gainToDb(averageAbsoluteLevel) * scale + offset;
console.log("Measure for 5 minutes: average level is:" + averageDbLevel);
}
window.setInterval(calculateAverage, 1000);
Your collectInterval timeout is never reinstated after the first time calculateAverage is called, unless the issue is something else not visible from the code.
In your code calculateAverage is called every 1000 milliseconds, but the values stored in levelMeasurements are not updated after the first window.clearInterval.
I made a simplified snippet without Tone lib:
var levelMeasurements = [];
//added this as a easy source of values
let count = 0;
function collectLevelMeasurements() {
// levelMeasurements.push(averagingLevel);
levelMeasurements.push(count++);
}
var collectInterval = window.setInterval(collectLevelMeasurements, 0);
function calculateAverage() {
window.clearInterval(collectInterval);
var avg = 0;
for (counter = 0; counter < levelMeasurements.length; counter++) {
avg += levelMeasurements[counter] / levelMeasurements.length;
}
averageAbsoluteLevel = Math.abs(avg);
averageDbLevel = averageAbsoluteLevel;
//prolly dont need tone lib for this example
// averageDbLevel = Tone.gainToDb(averageAbsoluteLevel) * scale + offset;
console.log("Measure for 5 minutes: average level is:" + averageDbLevel);
//reset these variables
levelMeasurements = [];
count = 0;
console.log(levelMeasurements)//empty array at this point
//reset the collectInterval!
collectInterval = window.setInterval(collectLevelMeasurements, 0);
}
window.setInterval(calculateAverage, 1000);
You can try following:
levelMeasurements.length = 0.
Or refer more solution at here: How do I empty an array in JavaScript?
I need the images to change from one to another each time the button is pressed. I have tried using SetTimeout, setInterval etc and none of these seem to work? Im not sure what I'm doing wrong
var list = [
"https://assets.publishing.service.gov.uk/media/559fbe1940f0b6156700004d/traffic-light-red.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe48ed915d1592000048/traffic-light-amber.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe3e40f0b6156700004f/traffic-light-green.jpg",
"http://thndl.com/images/1_3.png"
];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length)
index = 0;
var myVar = setInterval(function() {
ChangeLights()
}, 1000);
}
}();
<button type="button" onclick="changeLights()">Change Lights</button>
You are calling ChangeLights instead of changeLights. But even if you call it right, you create an interval with calling the same function each 1000 ms. That means at the second call, it create a new interval and calls it again and the actual interval call the function as well.
Solution: Separate initializing of the interval and the function for doing the work.
Start with startLights and call changeLights in the interval.
var list = [
"https://assets.publishing.service.gov.uk/media/559fbe1940f0b6156700004d/traffic-light-red.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe48ed915d1592000048/traffic-light-amber.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe3e40f0b6156700004f/traffic-light-green.jpg",
"http://thndl.com/images/1_3.png"
];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length) {
index = 0;
}
console.log(index);
}
function startLights() {
setInterval(changeLights, 1000);
}
<button type="button" onclick="startLights()">Change Lights</button>
Error
changeLights() != ChangeLights()
Warning
Is the setInterval() placing
Not apply the setInterval() inside the click function.In each time loop time second's are reduced.so its change more lower time seconds.So use with setInterval with in click and color change was separate
var list = [
"https://assets.publishing.service.gov.uk/media/559fbe1940f0b6156700004d/traffic-light-red.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe48ed915d1592000048/traffic-light-amber.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe3e40f0b6156700004f/traffic-light-green.jpg",
"http://thndl.com/images/1_3.png"
];
var index = 0;
function change() {
index = index + 1;
if (index == list.length)
index = 0;
console.log(list[index])
}
function changeLights(){
var myVar = setInterval(function() {
change()
}, 1000);
}
<button type="button" onclick="changeLights()">Change Lights</button>
As above answers indicate - the call to the function needs to be outside it. One alteration I would suggest is to use the modulus operator (index % 3) which will allow a constant cycling of the images without the need for the if statement. This works because the modulus operator gives the remainder after dividing the number by the operator - so modulus %3 will mean that for example if index is three - the remainder is 0, 4 gives 1 5 gives 2 and then 6 is back at 0. So you have a perfect cycling count giving the three values 0,1, and 2 without having to check for each one.
var list = [
"https://assets.publishing.service.gov.uk/media/559fbe1940f0b6156700004d/traffic-light-red.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe48ed915d1592000048/traffic-light-amber.jpg",
"https://assets.publishing.service.gov.uk/media/559fbe3e40f0b6156700004f/traffic-light-green.jpg",
"http://thndl.com/images/1_3.png"
];
var index = 0;
function changeLights() {
index +=1;
document.getElementById('imageSrc').textContent = 'Source: ' + list[index %3];
document.getElementById('lights').src = list[index %3];
}
var myVar = setInterval(function() {
changeLights()
}, 1000);
<p id="imageSrc"></p>
<img id = "lights"/>
I have a simple setInterval function that is done inside of a for loop. My goal is that I want the function to run on each position in the array, and once it reaches the end, I want it to stop. However, this is not happening. The timeout function is continuing to run infinitely. Can anyone explain where I'm going wrong and what I need to do to fix this?
JS
Keyhole.bufferArray = [Keyhole.twoMileBuffer, Keyhole.fiveMileBuffer, Keyhole.tenMileBuffer, Keyhole.twentyFiveMileBuffer];
var ticker = -1;
for(var i = 0; i < Keyhole.bufferArray.length; i++){
var populateServices = setInterval(function(){
++ticker;
addBuffersToService(Keyhole, i);
if(ticker >= Keyhole.bufferArray.length - 1){
ticker = -1;
clearInterval(populateServices);
}
}, 1000)
}
function addBuffersToService(Keyhole, index){
console.log(Keyhole);
}
Because you have a for loop that is making an interval for every index of the array. You should not be using the for loop if you are looping over the array with the interval. Remove the for loop.
The problem is that you overwrite your interval handler in loop. I suggest you to kepp handlers in array and remove them according to iterator varialble:
var ticker = -1;
var populateServices = [];
for(var i = 0; i < Keyhole.bufferArray.length; i++){
populateServices[ticker + 1] = setInterval(function(){
...
clearInterval(populateServices[ticker + 1]);
ticker = -1;
Note that array identifiers should be positive numbers so you should add +1 inside handlers array.
And don't forget to set ticker to -1 after clearInterval invokation.
I'm iterating over an array with a some loop to see if a time is in the past but I also want to return how many times the loop has run, how do I do that?
arr.some(function(a, i){
var date = Date.parse(a.start);
var now = new Date().getTime();
console.log(i);
return now-date < 0;
});
Edit: Solved this by just doing a for loop instead.
You can't return multiple objects in javascript. However, you can return a list of objects.
return [now-date < 0, i]
Count = 0;
arr.some(function(a, i){
Count = +Count + 1;
var date = Date.parse(a.start);
var now = new Date().getTime();
console.log(i);
return now-date < 0;
});
You could be able to make a counter, something like this.. basicly set count to 0 first and everytime the loop runs, count = old count + 1.