How to kill interval function dynamically [duplicate] - javascript

This question already has answers here:
Stop setInterval
(6 answers)
Closed 5 years ago.
I am working on the snippet below. Is there a way to check whether the setInterval() is really killed or still running in background processing?
Technically what I need to do is killing the JS setInterval whenever the .map is not in the page. My understanding is the setInterval() still running every 2 second just is not writing on the console because of if statement.
setInterval(
function() {
if ($(".map")[0]) {
console.log("Map is in the Page");
} else {
//Stop Interval
}
}, 2000);
setTimeout(function(){ $(".box").empty();
}, 9000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<div class="map">Map in Here</div>
</div>

You need to call clearInterval() to stop the execution of the intervalled function.
Here's an example:
let i = 3;
let interval = setInterval(function() {
if (i > 0) {
console.log("Running " + i--);
} else {
clearInterval(interval);
console.log("Stopped");
}
}, 2000);

In order to kill an interval or timeout you should assign it to a variable for referencing. The specific functions are: clearInterval(your interval reference variable name) and clearTimeout(your timeout reference variable name).
var yourInterval = setInterval(
function() {
console.log("Still running?"); //for testing purpose.
if ($(".map")[0]) {
console.log("Map is in the Page");
} else {
clearInterval(yourInterval); //it kills this interval, if the interval already terminated, it won't do anything harm, nor produce an error message in the browser console.
}
}, 2000);
setTimeout(function(){ $(".box").empty();
}, 9000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<div class="map">Map in Here</div>
</div>

Related

Making a timer using setInterval function in javascript but haveing problem with it in Javascript [duplicate]

This question already has answers here:
setInterval going too fast [duplicate]
(2 answers)
Closed 1 year ago.
I am making a timer using setInterval function in Javascript.
I make one set button and one delete button which will set/delete the interval when pressed it.
Here is my code:
var interval;
function sets(){
interval = setInterval(function(){
document.querySelector('div').textContent =
parseFloat(document.querySelector('div').textContent)+1;
},1000);
};
function del(){
window.clearInterval(interval);
document.querySelector('div').textContent = 0;
};
<button onclick = 'sets()'>Set</button>
<button onclick = 'del()'>Delete</button>
<div>0</div>
I found that when I keep pressing the set button, the div.textContent will increasing faster and faster as I pressed more the set button.
Do anyone know why does this happens and is there some ways that i could avoid it without making two buttons into one button?
Thanks for any helps and responds.
You can clear the previous interval if interval is assigned already
var interval;
function sets() {
// Here you can check if the interval is assigned already
// If assigned, use del() to clear it
if (interval) {
del()
}
interval = setInterval(function() {
document.querySelector('div').textContent =
parseFloat(document.querySelector('div').textContent) + 1;
}, 1000);
};
function del() {
window.clearInterval(interval);
document.querySelector('div').textContent = 0;
interval = null;
};
<button onclick='sets()'>Set</button>
<button onclick='del()'>Delete</button>
<div>0</div>

Javascript Behaviour [duplicate]

This question already has answers here:
Calling functions with setTimeout()
(6 answers)
Closed 2 years ago.
I am trying to make a seconds countdown with Javascript.
Here is my HTML
<div id="ban_container" class="error center">Please wait
<span id="ban_countdown" style="font-weight:bold">
45</span>
seconds before trying again
</div>
And my JS:
<script type="text/javascript">
var seconds = <?php echo $user->getBlockExpiryRemaining(); ?>;
function countdown(element) {
var el = document.getElementById(element);
if (seconds === 0) {
document.getElementById("ban_container").innerHTML = "done";
return;
}
else {
el.innerHTML = seconds;
seconds--;
setTimeout(countdown(element), 1000);
}
}
countdown('ban_countdown');
</script>
However for some reason, it is not waiting the timeout time, but instead executes countdown right away so that when I refresh the page it just displays "done" right away. I know it is actually being executed multiple times because if I do innerHTML += seconds + " "; it counts down from 45. Why is the timeout being bypassed?
setTimeout(countdown(element), 1000); executes your function with that argument and passes the result into setTimeout. You don't want that.
Instead, execute an anonymous function that calls your function:
setTimeout(function() {
countdown(el); // You used `el`, not `element`?
}, 1000);
If you'd like to pass an argument to a function by setTimeout, try this:
setTimeout(countdown, 1000, element);
The syntax of setTimeout is the following:
setTimeout(function,milliseconds,param1,param2,...)
It is because setTimeout is asynchroneous. Try this:
setTimeout(function(){
countdown('ban_countdown'); //or elemement
}, 1000);
This will make the function countdown execute after 1000 miliseconds.

javascript runs twice [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have this code in my section:
function showIt() {
document.getElementById("hid").style.visibility = "visible";
}
setTimeout("showIt()", 6000); // 1000 = 1 sec
function showIt() {
document.getElementById("hid2").style.visibility = "visible";
}
setTimeout("showIt()", 7000); // 1000 = 1 sec
I am trying to reveal two separate elements. But the code always seems to work with only the first element.
This comes first on the page
<div id="hid2" style="visibility: hidden" class="video-arrow">
<p>Ready for some help growing your business?</p>
<div class="arrow-bg"><img src="img/arrow-bg.png" alt=""></div>
</div>
And This Comes Second
<div id="hid" style="visibility: hidden" class="header-button">
<div class="header-button-center">
<a href="">
<p class="offer">
<u>YES!</u>I Want To Get Instant Access To Interactive Offer!
<span>ยป</span></p>
</a>
</div>
<p class="guarantee">No worries. Our offer comes with a
<b>30-Day Money-Back Guarantee!</b></p>
</div>
Due to the nature of the div layout I can't put both elements in the same hidden div, and... ideally, I would display them at different times.
You cannot have two different functions with the same name. Try to change name the second function:
function showIt() {
document.getElementById("hid").style.visibility = "visible";
}
setTimeout(showIt, 6000); // 1000 = 1 sec
function showIt2 {
document.getElementById("hid2").style.visibility = "visible";
}
setTimeout(showIt2, 7000); // 1000 = 1 sec
you have defined showIt() function twice, its better if you create single function and pass element id as function parameter like
function showIt(id) {
document.getElementById(id).style.visibility = "visible";
}
You have two different functions with the same name in your code, It's not correct.
Try this:
function showIt1() {
document.getElementById("hid").style.visibility = "visible";
}
setTimeout(showIt1(), 6000); // 1000 = 1 sec
function showIt2() {
document.getElementById("hid2").style.visibility = "visible";
}
setTimeout(showIt2(), 7000); // 7000 = 7 sec
OR you can also try this one:
function showIt(Id) {
document.getElementById(Id).style.visibility = "visible";
}
setTimeout(showIt("hid"), 6000); // 1000 = 1 sec
setTimeout(showIt("hid2"), 7000); // 7000 = 7 sec
Use Like
function showIt1() {
document.getElementById("hid").style.visibility = "visible";
}
setTimeout("showIt1()", 6000); // 1000 = 1 sec
function showIt2() {
document.getElementById("hid2").style.visibility = "visible";
}
setTimeout("showIt2()", 7000); // 1000 = 1 sec
Pretend you are the web browser and read your code, s-l-o-w-l-y.
function showIt() {
document.getElementById("hid").style.visibility = "visible";
}
// cool, some code. This defines function showIt
setTimeout("showIt()", 6000); // 1000 = 1 sec
// a to do item. He sent me a string instead of a function, so in 6 seconds
// I will call eval on "showIt()";
function showIt() {
document.getElementById("hid2").style.visibility = "visible";
}
// hmm, he changes his mind. OK, now this is function showIt
setTimeout("showIt()", 7000); // 1000 = 1 sec
// another to do item. Another string.
// So in 7 seconds I will execute "showIt()" means by using eval().
// 6 seconds go by.
// Time to run "showIt()". Oh, its a function call.
// Use the latest version of showIt(), displaying hid2.
// ...
// another second goes by
// Time to run "showIt()". Same function we called a second ago.
// Make hid2 visible again. Oh, it already is. Oh, well.
Key points:
setTimeout doesn't wait. It is very fast. It sets up something to execute later.
When "showIt()" is executed, showIt() is the second version
It is better to give setTimeout a function than a string that calls a function, especially for cases where the function is only called once. You can use an anonymous function within the setTimeout parameter list.
setTimeout(
function(){ document.getElementById("hid").style.visibility = "visible"},
6000);
setTimeout(
function(){ document.getElementById("hid2").style.visibility = "visible"},
7000);
See also: MDN docs for window.setTimeout()
function showIt() {
setTimeout(function(){document.getElementById("hid").style.visibility = "visible";},6000);
setTimeout(function(){document.getElementById("hid2").style.visibility = "visible";},7000);
}
I think the reason is that you have 2 functions named showIt. The second showIt will overwrite the first one. You can try with different function names.
You can use the following:
function showAndTimeOut (id, time)
{
showIt(id);
setTimeout(function(){/* Dummy anonymous function! */}, time); // 1000 = 1 sec
// or may be you can use below line instead of above two:
setTimeout(showIt(id), time);
}
function showIt(id)
{
document.getElementById(id).style.visibility = "visible";
}
For calling you can use,
showAndTimeOut ("hid", 6000);
showAndTimeOut ("hid1", 7000);

why setTimeout() only run my code once,at first time? [duplicate]

This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 8 years ago.
i use this javascript code to open two pictures and toggle a vertical menu by clicking on another picture. an know i want to run code without clicking on image, with a timer. so i wrote this code but it run only once at first time.
what's wrong with my code?
<script type="text/javascript">
$(document).ready(function () {
$("#lista2").slideToggle(1);
$curtainopen = false;
$(".rope").click(function () {
$(this).blur();
if ($curtainopen == false) {
var selected = $(this).val();
var image = $(".rope");
image.fadeOut('fast', function () {
$("#largeImg").attr('src', 'images/power-on.png');
image.fadeIn('fast');
});
$(".leftcurtain").stop().animate({ left: '-120px' }, 2000);
$(".rightcurtain").stop().animate({ left: '120px' }, 2000);
$("#R").attr('src', 'images/Right.gif');
$("#L").attr('src', 'images/Left.gif');
$curtainopen = true;
$("#lista2").slideToggle(2000);
$(this).attr('id', '1');
} else {
var selected = $(this).val();
var image = $(".rope");
image.fadeOut('fast', function () {
$("#largeImg").attr('src', 'images/power-off.png');
image.fadeIn('fast');
});
$(".leftcurtain").stop().animate({ left: '0px' }, 2000);
$(".rightcurtain").stop().animate({ left: '0px' }, 2000);
$curtainopen = false;
$("#lista2").hide();
$(this).attr('id', '0');
}
return false;
});
});
function startTimer() {
setTimeout($(".rope").click(), 4000);
}
</script>
use this to execute your code after a specific time interval
setInterval(function() {
$(".rope").click(); // this will execute after every 4 sec.
}, 4000);
use this to execute your code after a specific time delay
setTimeout(function() {
$(".rope").click(); // this will execute after 4 sec delay only once.
}, 4000);
use above according to your requirement
setTimeout need a function, When you are passing $(".rope").click() it is called immediately.
Use it like
function startTimer() {
setTimeout(function () {
$(".rope").click();
}, 4000);
}
setTimeout(function() {
$(".rope").click();
}, 4000);
because setTimeout needs a function, but $(".rope").click() calls itself immediatly (instead of assigning a function to be called). So you don't want to call a function but to pass it to setTimeout.
A timer implies repeating the function after each timeout. setTimeOut only delays a function once (after a given time, in milliseconds).
function startTimer() {
//do your stuff
$(".rope").click();
//repeats itself after 4 seconds
setTimeout(startTimer, 4000);
}
And do not forget to start it on document ready :
$(document).ready(function () {
startTimer();
...
}
I you don't want your function to be called immediately on page load, you can add an initial delay :
$(document).ready(function () {
setTimeout(startTimer, 5000); //the timer will start only 5 seconds after page load
...
}

setTimeout() is not waiting [duplicate]

This question already has answers here:
Calling functions with setTimeout()
(6 answers)
Closed 2 years ago.
I am trying to make a seconds countdown with Javascript.
Here is my HTML
<div id="ban_container" class="error center">Please wait
<span id="ban_countdown" style="font-weight:bold">
45</span>
seconds before trying again
</div>
And my JS:
<script type="text/javascript">
var seconds = <?php echo $user->getBlockExpiryRemaining(); ?>;
function countdown(element) {
var el = document.getElementById(element);
if (seconds === 0) {
document.getElementById("ban_container").innerHTML = "done";
return;
}
else {
el.innerHTML = seconds;
seconds--;
setTimeout(countdown(element), 1000);
}
}
countdown('ban_countdown');
</script>
However for some reason, it is not waiting the timeout time, but instead executes countdown right away so that when I refresh the page it just displays "done" right away. I know it is actually being executed multiple times because if I do innerHTML += seconds + " "; it counts down from 45. Why is the timeout being bypassed?
setTimeout(countdown(element), 1000); executes your function with that argument and passes the result into setTimeout. You don't want that.
Instead, execute an anonymous function that calls your function:
setTimeout(function() {
countdown(el); // You used `el`, not `element`?
}, 1000);
If you'd like to pass an argument to a function by setTimeout, try this:
setTimeout(countdown, 1000, element);
The syntax of setTimeout is the following:
setTimeout(function,milliseconds,param1,param2,...)
It is because setTimeout is asynchroneous. Try this:
setTimeout(function(){
countdown('ban_countdown'); //or elemement
}, 1000);
This will make the function countdown execute after 1000 miliseconds.

Categories

Resources