simplifying a multi-function in javascript - javascript

Hey I'm trying to figure out a way I might be able to simplify my code so that I will not have to have 38 of these functions but only have one that can run 38 different id's at separate times. This is a randomized script that tells the id element to land on a specific letter.
var randlet = 0;
var timesrun = 0;
function randomizer() {
randlet = Math.floor(Math.random() * 26);
timesrun += 1;
if (master[randlet] == letter[0]) {
$('#L1').css('background-position', master[randlet]);
clearInterval(interval);
} else {
if (timesrun == 100) {
master[randlet] = letter[0];
$('#L1').css('background-position', master[randlet]);
clearInterval(interval);
} else {
$('#L1').css('background-position', master[randlet]);
}
}
}
var interval = setInterval(function() {
randomizer();
}, 10);

For each element, set a class called 'randomise'. In the function, use the jquery .each method to iterate over each randomised element. If that element needs to have its value fixed, simp,y remove the 'randomise' class. When no more elements have the randomise class anymore, clear the timer.

Related

How can I stop a "setInterval" function?

i'm just starting out with javascript and I'm trying to make some sort of dashboard.
I would like the fuel status to go down by 1 every few seconds but i want it to stop at zero. Also, i was trying to set an alert when the fuel status reaches 20%, but obviously it doesnt work.
I have a few questions:
How can i "stop" the setInterval function when fuelStatus reaches 0?
I dont think i fully understand the topic with the functions so i believe my approach may not be correct. Do i need to write functions for every task that i want to do like checking the fuel? Should i have put testFuel in the fuelStatus function?
Thanks guys!
var fuelStatus = 100;
function Fuel() {
fuelStatus--; //number = -1;
console.log(fuelStatus);
document.getElementById("fuelStatus").innerHTML = fuelStatus + '%';
}
setInterval(function() {
Fuel()
}, 5000)
function testFuel() {
if (fuelStatus == 20) {
alert("critical fuel status")
}
}
Capture the ID returned by setInterval() and then use the clearInterval function, passing it the captured interval ID, to clear it.
var fuelStatus = 100;
function Fuel() {
fuelStatus--; //number = -1;
console.log(fuelStatus);
document.getElementById("fuelStatus").innerHTML = fuelStatus + '%';
}
const runFuelInterval = setInterval(function() {
Fuel()
}, 5000)
function testFuel() {
if (fuelStatus == 20) {
alert("critical fuel status")
clearInterval(runFuelInterval);
}
}

How can I set timers in slideshow to show as selected?

I have to create a slideshow, using an array of images and have that set on a timer. There is a drop-down menu with slow, medium, and fast options and the pictures need to transition with accordance to the drop down option selected. Whenever I execute this code in a web browser the code repeats itself, while doubling, as I read the value of i in the console.
I have tried using a while and a do-while loop to have the images on a rotation.
I have also tried putting the if-statements outside and below/above the function.
<script>
var i = 0;
function changeImg(){
if (x == 'slow'){
setInterval("changeImg()", 5000);
} else if (x == 'medium'){
setInterval("changeImg()", 3000);
} else if (x == 'fast') {
setInterval("changeImg()", 1000);
} else {}
while (i < 3){
console.log(i);
document.slide.src = sportsArray[i];
i++;
}
console.log(i);
console.log(sportsArray);
}
</sctipt>
First, I would read up on MDN's docs on setInterval() and clearInterval to fill in the knowledge gaps that lead you to approach the problem this way.
You are recursively calling changeImg() in your code which I believe is causing the issue you describe as:
the code repeats itself, while doubling, as I read the value of i in the console
Also, your while loop will run immediately when calling changeImg() which also does not appear to be desired in this situation.
setInterval() mimics a while loop by nature. There is no need for a while loop in this code. Below is a solution that I hope you can use as a reference. I separated the code to determine the interval into a function the getIntervalSpeed.
function changeImg(x) {
var getIntervalSpeed = function(x) {
if (x === 'slow') {
return 5000;
} else if (x === 'medium') {
return 3000;
} else if (x === 'fast') {
return 1000;
} else {
return 3000;
// return a default interval if x is not defined
}
};
var i = 0;
var slideShow = setInterval(function() {
if (i >= sportsArray.length) {
i = 0; // reset index
}
document.slide.src = sportsArray[i]; // set the slide.src to the current index
i++; // increment index
}, getIntervalSpeed(x));
// on click of ANY button on the page, stop the slideshow
document.querySelector('button').addEventListener('click', function() {
clearInterval(slideShow);
});
}

Display a sequence of images in 1 position stored in an object js

I'd like to have an object of images and then loop through them to display each one with a certain interval of time between each one.
Store images in an object:
var images = [
{ name: 'image1', image: 'image1.jpg' },
{ name: 'image2', image: 'image2.jpg' },
{ name: 'image3', image: 'image3.jpg' }
]
Create a loop to go through each image in the object and each time it cycles through it changes the source of the div to the image.
Lastly i'd like the images to stop cycling through the loop of a button is clicked.
So far I have the above object setup along with a function containing a counter which loops through the items in the object.
var add = (function() {
var counter = images.length - 1;
return function() {
if(counter === images.length - 1) {
counter = 0;
} else {
counter+=1;
}
return counter;
}
})();
I then used setInterval to change the src every 0.5 seconds.
setInterval(
function() {
var imageDiv = document.getElementById('image');
var tester = images[add()];
imageDiv.src = tester.image;
}
, 500);
The above seems to console log the correct image OK, but its not changing the source and displaying one of the images once every 0.5 seconds.
Can anyone provide a pointer to help me update the src?
Thank you
A Loop is not necessary here, you can manually keep track of the Current Image like i did with the imgIndex variable and increment it each time the function changeImg() is called. I set that variable back to 0 after it reaches the last image, so it will repeat the Image-Order afterwards.
In the setInterval Function (2nd Argument) you can set the Time each Image should be displayed.
You dont need to worry about Images being loaded multiple times, since
we just replace the src attribute the Browser will handle it.
Any further questions?
images = [
{"name":"img1", "src":"https://phinest.com/wp-content/uploads/2017/02/Maya_Beano_Phinest_4-800x800.jpg"},
{"name":"img2", "src":"https://www.pixel-creation.com/wp-content/uploads/3d-nature-wallpapers-wallpaper-cave-800x800.jpg"},
{"name":"img3", "src":"https://img00.deviantart.net/5fdc/i/2009/162/9/0/nature_stock_14_by_dezzan_stock.jpg"},
{"name":"img4", "src":"https://www.secretescapes.com/inlombardia/img/content/link--nature.jpg"},
{"name":"img5", "src":"https://www.mappingmegan.com/wp-content/uploads/2017/04/sunset-2177324_1920-001.jpg"}
];
imgIndex = 0;
function changeImg(){
document.getElementById("slideshow").src = images[imgIndex].src;
if(images.length > imgIndex+1){
imgIndex++;
} else {
imgIndex = 0;
}
}
changeImg();
setInterval(changeImg, 2000)
<img id="slideshow" src=""/>
I think you have a problem with the counter fn. Please try this; it starts from 0, ends on images.length - 1 and then restarts to 0:
var add = (function(len) {
var counter = 0;
return function() {
if(counter === len) {
counter = 0;
}
return counter++;
}
})(images.length); // It's not required, but I also recommend you passing images.length as a parameter
Also, if you want to stop the interval, you just have to do something like this:
// Now myInterval is a numbered ID
var myInterval = setInterval(myFn, myTime);
// Something happens here and then..
// Your interval is stopped
clearInterval(myInterval);

How to slow down a loop with setTimeout or setInterval

I have an array called RotatorNames. It contains random things but let's just say that it contains ["rotatorA","rotatorB","rotatorC"].
I want to loop through the array, and for each item i want to trigger a click event. I have got some of this working, except that the everything get's triggered instantly. How can i force the loop to wait a few seconds before it continues looping.
Here's what i have.
function Rotator() {
var RotatorNames = ["rotatorA","rotatorB","rotatorC"];
RotatorNames.forEach(function(entry){
window.setTimeout(function() {
//Trigger that elements button.
var elemntBtn = $('#btn_' + entry);
elemntBtn.trigger('click');
}, 5000);
});
}
You can run this to see what my issue is. http://jsfiddle.net/BxDtp/
Also, sometimes the alerts do A,C,B instead of A,B,C.
While I'm sure the other answers work, I would prefer using this setup:
function rotator(arr) {
var iterator = function (index) {
if (index >= arr.length) {
index = 0;
}
console.log(arr[index]);
setTimeout(function () {
iterator(++index);
}, 1500);
};
iterator(0);
};
rotator(["rotatorA", "rotatorB", "rotatorC"]);
DEMO: http://jsfiddle.net/BxDtp/4/
It just seems more logical to me than trying to get the iterations to line up correctly by passing the "correct" value to setTimeout.
This allows for the array to be continually iterated over, in order. If you want it to stop after going through it once, change index = 0; to return;.
You can increase the timeout based on the current index:
RotatorNames.forEach(function(entry, i) {
window.setTimeout(function() {
//Trigger that elements button.
var elemntBtn = $('#btn_' + entry);
elemntBtn.trigger('click');
}, 5000 + (i * 1000)); // wait for 5 seconds + 1 more per element
});
Try:
var idx = 0;
function Rotator() {
var RotatorNames = ["rotatorA", "rotatorB", "rotatorC"];
setTimeout(function () {
console.log(RotatorNames[idx]);
idx = (idx<RotatorNames.length-1) ? idx+1:idx=0;
Rotator();
}, 5000);
}
Rotator();
jsFiddle example
(note that I used console.log instead of alert)
Something like this should do what you're after:
function Rotator(index){
var RotatorNames = ["rotatorA","rotatorB","rotatorC"];
index = (index === undefined ? 0 : index);
var $btn = $("#btn_"+RotatorNames[index]);
$btn.click();
if(RotatorNames[index+1]!==undefined){
window.setTimeout(function(){
Rotator(index+1);
}, 500);
}
}

Loop through js array continually with pauses

I want to loop over an array continuously on click. Extra props if you can work in a delay between class switches :-)
I got this far:
// Define word
var text = "textthing";
// Define canvas
var canvas = 'section';
// Split word into parts
text.split();
// Loop over text
$(canvas).click(function() {
$.each(text, function(key, val) {
$(canvas).removeAttr('class').addClass(val);
});
});
Which is not too far at all :-)
Any tips?
The following will wait until you click the selected element(s) in the var el. In this example var el = $('section') will select all <section>...</section> elements in your document.
Then it will start cycling through the values in cssClassNames, using each, in turn as the css class name on the selected element(s). A delay of delayInMillis will be used between each class change.
var cssClassNames = ['c1', 'c2', 'c3'];
var el = $('section');
var delayInMillis = 1000;
// Loop over text
el.click(function() {
var i = 0;
function f() {
if( i >= cssClassNames.length ) {
i = 0;
}
var currentClass = cssClassNames[i];
i += 1;
el.removeClass().addClass(currentClass);
setTimeout(f, delayInMillis);
}
f();
});
I believe you want a delay of X milliseconds between removing a class and adding a class. I'm not sure that you have to have the lines marked // ? or even that they do the job, but what you do have to have is a way to get the value's into the function. Also, the setTimeout anon function might not actually need the parameters, but it should give you an idea.
$(canvas).click(function() {
$.each(text, function(key, val) {
$(canvas).removeAttr('class')
var $canvas = $(canvas) //?
var class_val = val //?
setTimeout(function ($canvas, class_val) {
$canvas.addClass(class_val);
}, 2000);
});
});
Edit: I'd do this instead
function modify_element($element, class_name){
$element.removeClass('class');
setTimeout(function ($element) {
$element.addClass(class_name);
}, 1000);
//adds the class 1 second after removing it
}
$(canvas).click(function() {
$.each(text, function(key, val) {
setTimeout(modify_element($(canvas), val),2000);
//this will loop over the elements with 2 seconds between elements
});
});
"loop over an array continuously" this sounds like a infinite loop, I don't think you want that. About pausing the loop, this is possible, you can use this

Categories

Resources