How can I stop a "setInterval" function? - javascript

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);
}
}

Related

How to use setInterval() to call a click function periodically within another function?

this is my first programming in Java. I have two functions, #start and #reset. I want to use setInterval to use #reset function within #start after every 10 seconds.
Here are the two functions. First is #start
$('#start').click(function() {
// Calculate the amount of time in milliseconds to run for
var timeleft_s = Math.round(
parseInt($('#hours' ).val())*3600 +
parseInt($('#minutes').val())*60 +
parseInt($('#seconds').val())*1
);
if (timeleft_s > 2147483647) { // Max unsighed 32 bit value
alert("That's too long. Pick a shorter time.");
return;
}
if (APP.last_sent_status !== null && APP.last_sent_status !== APP.status) {
return false;
}
// 0 : not started
// 1 : running
// 2 : stopped
switch(APP.status) {
case 0:
APP.resumeMCA(APP.channel, timeleft_s);
APP.last_sent_status = 1;
break
case 1:
APP.stopMCA(APP.channel);
APP.last_sent_status = 2;
break
case 2:
APP.resumeMCA(APP.channel, timeleft_s);
APP.last_sent_status = 1;
break
default:
break
}
APP.updateButtonStates();
});
Here is the reset function
$('#reset').click(function() {
APP.resetHistogram(APP.channel);
});
I want to use setInterval inside the start function make sure the reset function executes after every 10 seconds.
Here is what I have tried so far with no luck. Any help is appreciated:
$('#start').click(function() {
// Calculate the amount of time in milliseconds to run for
var timeleft_s = Math.round(
parseInt($('#hours' ).val())*3600 +
parseInt($('#minutes').val())*60 +
parseInt($('#seconds').val())*1
);
if (timeleft_s > 2147483647) { // Max unsighed 32 bit value
alert("That's too long. Pick a shorter time.");
return;
}
if (APP.last_sent_status !== null && APP.last_sent_status !== APP.status) {
return false;
}
// 0 : not started
// 1 : running
// 2 : stopped
switch(APP.status) {
case 0:
APP.resumeMCA(APP.channel, timeleft_s);
APP.last_sent_status = 1;
break
case 1:
APP.stopMCA(APP.channel);
APP.last_sent_status = 2;
break
case 2:
APP.resumeMCA(APP.channel, timeleft_s);
APP.last_sent_status = 1;
break
default:
break
}
setInterval(#reset,10000)
APP.updateButtonStates();
});
function resetFunction(){
APP.resetHistogram(APP.channel);
}
$('#reset').click(resetFunction);
then replace
setInterval(#reset,10000) with
setInterval(resetFunction,10000)
since you defined the function to be called on #reset click as anonymous there's no reference as such by which you can call it.
so you define it by giving it a name, and then use that in place of onclick function as well as inside your start function
I am not totally sure of this answer. If you are trying to start a setInterval inside of the onclick of #start, here's what I think you could do:
setInterval(() => $("#reset").onclick(),10000);

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);
});
}

Right way to execute all if-bodies on the first method call

I use JavaScript to display a binary clock on a website. When the site is first loaded, the clock needs to be set to the right time and then updated.
What is the right way to get this behaviour? Right now I have a var that is checked on every update and is set to false after the first run.
Would it be better to copy the function, remove the conditions and have it call the other function?
This is the function:
time.firstRun = true;
function updateBinaryClock() {
var now = moment().toObject();
var bin;
if (time.showClockWithSeconds) {
bin = toSixBit(now.seconds.toString(2));
setColor(".binSec", bin);
}
if (now.seconds == 0 || time.firstRun) {
bin = toSixBit(now.minutes.toString(2));
setColor(".binMin", bin);
}
if (now.minutes == 0 || time.firstRun) {
bin = toSixBit(now.hours.toString(2));
setColor(".binHour", bin);
}
if (time.firstRun) {
time.firstRun = false;
}
setTimeout(updateBinaryClock, 0.1 * 1000);
}
Your function will saturate your ram soon, because you forgot to clear timeout on every function execution.
You could use setInterval instead of setTimeout:
function updateBinaryClock() {
aux_updateBinaryClock(true);
setInterval(aux_updateBinaryClock, 100); // 0.1*1000
}
function aux_updateBinaryClock(isFirstRun) {
var now = moment().toObject(),
bin;
if (time.showClockWithSeconds) {
bin = toSixBit(now.seconds.toString(2));
setColor(".binSec", bin);
}
if (now.seconds === 0 || isFirstRun) {
bin = toSixBit(now.minutes.toString(2));
setColor(".binMin", bin);
}
if (now.minutes === 0 || isFirstRun) {
bin = toSixBit(now.hours.toString(2));
setColor(".binHour", bin);
}
}
updateBinaryClock();
Also note that setInterval and setTimeout are inaccurate, there are many more accurate implementations of setInterval and setTimeout (es. this or this)
What I would do is separate it into 2 functions.
function initBinaryClock() {
}
function updateBinaryClock() {
requestAnimationFrame(updateBinaryClock);
}
window.addEventListener("load", function loader(){
window.removeEventListener("load", loader, false);
initBinaryClock();
updateBinaryClock();
}, false);

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);
}
}

simplifying a multi-function in 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.

Categories

Resources