I can't clear interval - javascript

I have a problem with the interval, which I can not clear after calling the function with a value.
The interval continues to increase the number and returns the percentage of the width.
Here my code:
function loadingClient(data) {
var loadingClientDiv = document.getElementById('loadingClient');
var percentageLoading = document.getElementsByClassName('percentageLoading');
var charge = 1;
var intervalLoadingClient = setInterval(barCharge, 1000);
function barCharge() {
if (charge >= 76) {
clearInterval(intervalLoadingClient);
} else {
++charge;
$(percentageLoading).css("width", charge + "%");
}
}
if (data === "100") {
clearInterval(intervalLoadingClient);
$(percentageLoading).css("width", "100%");
setTimeout(closeLoadingClient, 5000);
setTimeout(removeLoadingClient, 7000);
function closeLoadingClient() {
$(loadingClientDiv).hide("fade", 1000);
}
function removeLoadingClient() {
$(loadingClientDiv).remove();
}
}
}
loadingClient();

#hudolfhess is correct, you need to be using clearInterval instead of clearTimeout.
Also,
If you are trying to do something like this it wont work.
loadingClient() //Should start the interval.
loadingClient("100") //Should clear the interval, but doesn't.
you are trying to do? If so, you need to delcare intervalLoadingClient outside of the scope and avoid re-declaration of the variable when you call the method with parameters.
var intervalLoadingClient;
function loadingClient(data) {
var loadingClientDiv = document.getElementById('loadingClient');
var percentageLoading = document.getElementsByClassName('percentageLoading');
var charge = 1;
intervalLoadingClient = intervalLoadingClient || setInterval(barCharge, 1000);
function barCharge() {
if (charge >= 76) {
clearInterval(intervalLoadingClient);
} else {
++charge;
$(percentageLoading).css("width", charge + "%");
}
}
if (data === "100") {
clearInterval(intervalLoadingClient);
$(percentageLoading).css("width", "100%");
setTimeout(closeLoadingClient, 5000);
setTimeout(removeLoadingClient, 7000);
function closeLoadingClient() {
$(loadingClientDiv).hide("fade", 1000);
}
function removeLoadingClient() {
$(loadingClientDiv).remove();
}
}
}
loadingClient(); //Starts the interval
loadingClient("100"); //Ends the interval.

Related

Can't Implement Javascript Animation Logic

I want to implement some logic in my Javascript animation, but wherever I try to implement it, it never works. I am trying to make my navigationOpen true when the animation is done. But what happens is when I set it in the renderSlideOutAnimation() the if statement runs before the renderSlideOutAnimation function.
function openSlideNavigation() {
var navigationSlideOut = document.getElementById("navigation-slide");
var naviationTrigger = document.getElementById('menu-dots');
var navigationOpen = true;
function renderSlideOutAnimation() {
var widthValue = 0;
var interval = setInterval(frame, 17.5);
function frame() {
if (widthValue == 100) {
clearInterval(interval);
} else {
widthValue++
navigationSlideOut.style.width = widthValue + "vw"
}
}
}
if (navigationOpen == true){
renderSlideOutAnimation();
}
}

clearInterval and set it again after x seconds

I want to do simple interval with with if, It is checking a variable's value and doing a function again().
again function contains clearInterval, i++ and setTimeout to call interval again after x seconds
var speed = 1000;
var wait = 0;
var i = 0;
function init() {
setInterval(function() {
if (i >= 6) i = 0;
if (i == 4) {
wait = 5000;
again(wait);
} else {
document.body.innerHTML = i;
i++;
}
}, speed);
}
function again(time) {
clearInterval(init());
i++;
setTimeout(function() {
setInterval(init(), speed);
}, time);
}
init();
I expect output like this:
1, 2, 3, Waiting x sec's , 5, 1, 2, ...
but code is doing some thing crazy, Its going faster and faster. I don't know why.
Here's a codepen with example (can crash your browser!)
Can you fix it and explain? Thanks
You are not clearing interval but use function inside clearInterval method. Method init which is used has no return statement so clearInterval gets undefined in attribute, so it is not clearing nothing.
Fixed code:
var speed = 1000;
var wait = 0;
var i = 0;
var interval=null;
function init() {
interval = setInterval(function() {
if (i >= 6) i = 0;
if (i == 4) {
wait = 5000;
again(wait);
} else {
document.body.innerHTML = i;
i++;
}
}, speed);
}
function again(time) {
clearInterval(interval);
i++;
setTimeout(function() {
init()
}, time);
}
init();
Function setInterval returns interval id and function clearInterval in attribute should get id of interval which we want to stop, so I created interval variable to save id. I am using this variable in clearInterval.
This is a small example how changing the delay of a setInterval call.
(function iife() {
var timer = null,
counter = 0;
function task() {
counter += 1;
console.log(counter);
// condition: every four reps
if (counter % 4 === 0) {
console.log("changed speed to 4 seconds");
return start(4000);
}
// condition: every seven reps
if (counter % 7 === 0) {
console.log("changed speed to 2 seconds");
return start(2000);
}
}
function start(delay) {
clearInterval(timer);
console.log("runs every " + delay + " miliseconds");
timer = setInterval(task, delay);
}
start(1000);
}());

Changer SetInterval Values After Interval

If I can try to make everyone understand what I am looking for, I am looking for the value of the interval to change to lets say "5000ms" after "1000ms" and then it would go on to the next value such as "2000ms" and repeat all over again! The current code I have is pretty much a stopwatch, It adds the number 1 to a paragraph every 1000ms. Any help is extremely appreciated!
<script>
function myFunction() {
clicks += 1;
}
setInterval(myFunction, 1000);
var clicks = 0;
function myFunction() {
clicks += 1;
document.getElementById("demo").innerHTML = clicks;
// connects to paragraph id
}
</script>
<p id="demo"></p>
<!--connects to getElementById-->
Don't use setInterval - this functions will perform the action in any given interval, which you set once.
Use setTimeout instead. Which performs the action only once after given interval, and then call it again and again with different interval values.
what about this
<script>
var clicks = 0;
myFunction(1000);
function myFunction( currentInterval ) {
clicks ++;
document.getElementById("demo").innerHTML = clicks;
if ( currentInterval == 1000 )
{
currentInterval = 5000;
}
else if ( currentInterval == 5000 )
{
currentInterval = 2000;
}
else
{
currentInterval = 1000;
}
setTimeout( function(){ myFunction( currentInterval ) }, currentInterval );
}
</script>
<p id="demo"></p>
you should try using recursive timeout instead of interval
var timeout = 1000;
var timer;
function startTimer() {
clearTimeout(timer);
timer = setTimeout(function() {
console.log('tick');
startTimer();
}, timeout);
}
startTimer();
// timeout = 2000
// timeout = 500
// clearTimeout(timer); to cancel
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
This might look a little complicated but you can try something like this:
JSFiddle.
(function() {
var interval = null;
var limit = 5;
function initInterval(callback, index) {
var msToSec = 1000;
if (interval) {
clearInterval();
}
console.log("Delay: ", index)
interval = setInterval(callback, index * msToSec);
}
function clearInterval() {
window.clearInterval(interval);
interval = null;
}
function resetInterval(callback, count) {
clearInterval();
initInterval(callback, count);
}
function main() {
var count = 1;
var notify = function() {
console.log("Hello World: ", count);
var _nextCount = ((count++) % limit) + 1;
if (count < 10) {
resetInterval(notify, _nextCount);
} else {
console.log("Stoping loop...");
clearInterval();
}
}
initInterval(notify, count);
}
main()
})()

setTimeout() method won't execute

I have written a script, but i want to limit execution time for some functions. I decided to try setTimeout() method, however it results in no time out when i execute the program, i.e. setTimeout() does not work.
setTimeout(rollDice(), 6000) is the line that executes instantly
Here is my code :
function rollDice() {
diceOne = Math.round(5 * Math.random() + 1);
diceTwo = Math.round(5 * Math.random() + 1);
}
function mainFunction() {
playerAI.playing = true;
playerOne.playing = true;
currentScore = 0;
playerAI.totalScore = 0;
playerOne.totalScore = 0;
while (playerAI.playing == true && playerOne.playing == true) {
makeMove();
}
}
function makeMove() {
if (who == 0) {
aiStrat();
game();
}
else {
var confirmAction = confirm("Kas soovite visata täringuid?");
if (confirmAction) {
decision = 1;
}
else {
decision = -1;
}
game();
}
}
function game() {
if (decision == 1) {
setTimeout(rollDice(), 6000); // <--- THIS GETS EXECUTED INSTANTLY
if (diceOne != 1 && diceTwo != 1){
currentScore += diceOne + diceTwo;
//and so on
The code should look like this:
setTimeout(rollDice, 6000);
By adding the parentheses, you're calling the function and setting a timer for calling whatever that function returns. You'll want to pass the function object itself.
You can't immediately use diceOne and diceTwo after setting the timeout. You have to put that code in the timeout function as well, for example:
setTimeout(function() {
rollDice();
if (diceOne != 1 && diceTwo != 1){
currentScore += diceOne + diceTwo;
...
}, 6000);
That's because the code after setTimeout will not wait before the timeout has finished.
Try this:
setTimeout(function(){
rollDice()
}, 6000)
There is no need of Brackets when calling rollDice Function.
setTimeout(rollDice, 6000);
I would use something like this:
setTimeout(function(){rollDice()}, 6000);

Infinite Loop in Page Redirection Function of JavaScript

I am now working on a piece of code of JavaScript which will be used to redirect a page with a shown counter. The problem is, when counter reaches 0, countDown() function gets in an infinite loop which causes the page to remain the same. And of course, I could not resolve the problem yet. Can anyone help?
You can see the problem here:
http://kibristaodtuvarmis.com/index.html
Code is shown below:
var time = 10;
var page = "http://blog.kibristaodtuvarmis.com";
function countDown()
{
if (time == 0)
{
window.location = page;
return(0);
}
else
{
time--;
gett("container").innerHTML = time;
}
}
function gett(id)
{
if(document.getElementById) return document.getElementById(id);
if(document.all) return document.all.id;
if(document.layers) return document.layers.id;
if(window.opera) return window.opera.id;
}
function init()
{
if(gett("container"))
{
setInterval(countDown, 1000);
gett("container").innerHTML = time;
}
else
{
setTimeout(init, 50);
}
}
document.onload = init();
EDIT:
I have done the below changes in countDown() function and problem is resolved:
var control = false;
function countDown()
{
if (time == 0 && control == false)
{
control = true;
window.location = page;
return(0);
}
else if (time > 0)
{
time--;
gett("container").innerHTML = time;
}
else
{
return(0);
}
}
I would do something like this:
var b = false;
if (time == 0 && b == false)
{
b = true;
window.location = page;
return(0);
}
Try this part of code for by replacing your complete javascript Code :
var time = 10;
var page = "http://blog.kibristaodtuvarmis.com";
function startCount() {
time = time - 1;
console.log(time);
document.getElementById("container").innerHTML = time;
startCounter();
}
function startCounter() {
if (time !== 0) {
setTimeout(function () {
startCount();
},1000);
} else {
location.href = page;
}
}
if (window.addEventListener) {
window.addEventListener("load", startCount, false);
} else if (el.attachEvent) {
window.attachEvent("load", startCount);
}
I tried it, It works.
Tell me your reply after testing.
Are you wanting it to stop at 0? Assign the setInterval to a var and then use clearInterval if 0
your setIinterval continues executing before change the window.location and then causes this loop because time is 0 and should launch window.location again
you should clear the interval
var IdInterval = setInterval(function () {
//.... code
}, 10000);
and after the first execution of countDown with time==0 then:
clearInterval(IdInterval);

Categories

Resources