How to stop setInterval? - javascript

<span id="ccc">10</span> <span id="start">start</span> <span id="stop">stop</span>
$('#start').click(function(){
var c = $('#ccc').text();
var inter = setInterval(function() {
c--;
$('#ccc').text(c);
}, 1000);
});
$('#stop').click(function(){
clearInterval(inter);
});
how i must rewrite this for correctly use STOP?
LIVE: http://jsfiddle.net/c3hZh/

inter needs to be in-scope for both functions. Wrap both functions with a closure so that you can avoid polluting the global namespace with a new variable.
(function ($) {
var inter;
$('#start').click(function(){
var c;
c = parseInt($('#ccc').text()); //make sure you're getting a numeric value
//don't forget to clear any existing interval before setting a new one:
if (inter) {
clearInterval(inter);
}
inter = setInterval(function() {
c--;
$('#ccc').text(c);
}, 1000);
});
$('#stop').click(function() {
clearInterval(inter);
});
}(jQuery));

inter is a local variable.
It doesn't exist outside your callback.
You need to use a global variable.

var inter = 0;
$('#start').click(function(){
var c = $('#ccc').text();
inter = setInterval(function() {
c--;
$('#ccc').text(c);
}, 1000);
});
$('#stop').click(function(){
clearInterval(inter);
});

Related

setInterval and clearInterval. Smth went wrong

So, I have initialized my var with setInterval.
I want to stop and to start it. And I wish to have this control as often as I would like to.
This is the code
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function myStopFunction() {
clearInterval(myVar);
}
function myStartFunction() {
setInterval(myTimer, 1000);
//setInterval(myVar, 1000);
}
</script>
jsfiddle.net/adeneo/g8jmccfu/1
I press "Hold" button and it's works nice. Then I click "Continue" and this works nice too. And then I click "Hold" again... and it doesn't work.
I'd like appreciate any help and any suggestions.
You forgot to reassign the new timer ID to myVar (which I called interval):
var interval = setInterval(myTimer, 1000);
function myTimer() {
// ...
}
function myStopFunction() {
clearInterval(interval);
}
function myStartFunction() {
interval = setInterval(myTimer, 1000);
}
Your variable still contained the ID of the old interval, which made clearInterval(myVar) do nothing.
Use this code, you need to define a variable
var myVar;
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function myStartFunction() {
myVar = setInterval(myTimer, 1000);
}
myStartFunction();
function myStopFunction() {
clearInterval(myVar);
}

Javascript increasing animation

I have the following part of code:
<script>
$(function() {
var ele = $('#clients');
var clr = null;
var rand = 0;
(loop = function() {
clearTimeout(clr);
(inloop = function() {
ele.html(rand+=1);
if(clr==1000) {
return;
}
clr = setTimeout(inloop, 5);
})();
})();
});
</script>
How can i create a second function which will count until another number in the same page? Tried to do a few tests without success..
I tried this:
<script>
$(function() {
var ele = $('#products');
var clr = null;
var rand = 0;
(loop = function() {
clearTimeout(clr);
(inloop = function() {
ele.html(rand+=1);
if(clr==151) {
return;
}
clr = setTimeout(inloop, 5);
})();
})();
});
</script>
But the first function counts only until 2.
Two problems:
You shouldn't use the return value of setTimeout like this - it's not guaranteed to be an incrementing integer, and even when it is, it's global to the page and you can't reset it. Since you're already keeping a count in rand, you can use that to terminate your loop instead of clr.
As pointed out by #putvande, you're overwriting a global inloop variable with your second loop, and they will therefore interfere with each other - you need to declare a local variable.
Also your clearTimeout isn't doing anything useful, and you don't actually need your clr variable...
$(function() {
var ele = $('#clients');
var rand = 0;
var inloop;
(loop = function() {
(inloop = function() {
ele.html(rand+=1);
if(rand==1000) {
return;
}
setTimeout(inloop, 5);
})();
})();
});
$(function() {
var ele = $('#products');
var rand = 0;
var inloop;
(loop = function() {
(inloop = function() {
ele.html(rand+=1);
if(rand==151) {
return;
}
setTimeout(inloop, 5);
})();
})();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clients"></div>
<div id="products"></div>
Now you can extract the common code and reuse it:
function countTo(ele, count) {
var rand = 0;
var inloop;
(inloop = function() {
ele.html(rand += 1);
if(rand == count) {
return;
}
setTimeout(inloop, 5);
})();
}
$(function() {
countTo($('#clients'), 1000);
countTo($('#products'), 151);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clients"></div>
<div id="products"></div>
It's because inloop is not defined anywhere and will therefore be defined on a global scope. In your second function, you override this variable. So your first function runs once, and then your second one will run until it stops.
So you should define the inloop inside your loop function:
...
(loop = function() {
var inloop;
clearTimeout(clr);
(inloop = function() {
...
Fiddle
But what you probably want is to rewrite it so you could just call your same functionality twice with some parameters.

Stop countdown javascript

i'm new in js and i have created simple countdown but i want to stop it if the value of count = 0
this my script
var no;
no = 5;
$(document).ready(
function(){
timer();
var t = setInterval(timer, 1000);
var c = setInterval(cek, 1000);
}
);
function timer(){
no--;
$('.timer').html(no);
}
function cek(){
if(no===0){
alert('done');
clearInterval(t);
clearInterval(c);
}
}
Thi is the link of my script : here
You can try doing this (there is no need to create 2 async timers when you can achieve the same with only one such interval):
var t;
var no = 5;
$(document).ready(function() {
t = setInterval(function() {
timer();
cek();
}, 1000);
});
function timer() {
no--;
console.log('NO');
$('.timer').html(no);
}
function cek() {
if(no===0) {
alert('done');
clearInterval(t);
}
}
You can check an updated version of your fiddle # http://jsfiddle.net/bG8yr/5/
Simple issue, your variable was defined in the ready/anonymous function closure. I want to second the fact this is no the best way to do it. In the future inspect the fiddle and look for console errors. Its an easy way to figure out whats going wrong.
http://jsfiddle.net/cYWBL/
var no, t, c, no = 5;
$(document).ready(
function(){
timer();
t = setInterval(timer, 1000);
c = setInterval(cek, 1000);
}
);
function timer(){
no--;
$('.timer').html(no);
}
function cek(){
if(no===0){
alert('done');
clearInterval(t);
clearInterval(c);
}
}
This will do exactly what you want:
var no,
t;
no = 5;
$(document).ready(
function () {
t = setInterval(timer, 1000);
}
);
function timer() {
no--;
$('.timer').html(no);
if (no === 0) {
alert('done');
clearInterval(t);
}
}
here is the javascript code which you required. just include one if-else which is very simple. all code is your. just add if timer goes less than 0 than do nothing else coutdown.
var no;
no = 5;
$(document).ready(
function(){
timer();
var t = setInterval(timer, 1000);
var c = setInterval(cek, 1000);
}
);
function timer(){
no--;
if(no<0){ //nothing }
else{
$('.timer').html(no);
}
}
function cek(){
if(no===0){
alert('done');
clearInterval(t);
clearInterval(c);
}
}
Here is the answer
http://jsfiddle.net/bG8yr/4/
var no;
no = 5;
var isRunning=false;
$(document).ready(
function(){ isRunning=true;
timer();
var t = setInterval(timer, 1000);
var c = setInterval(cek, 1000);
}
);
function timer(){
if(isRunning){
no--;
$('.timer').html(no+":"+isRunning);
}
}
function cek(){
if(no===0&&isRunning){
isRunning=false;
alert('done');
clearInterval(t);
clearInterval(c);
}
}
Try this :
function timer(){
no--;
if (no >= 0)
$('.timer').html(no);
}

Clear interval from within a closure

I'm trying to clear an interval when the user hovers over an element and then start it up again when they hover off an element. I think this is a closure but I'm not sure, hopefully my code will make sense what I'm trying to do.
var rotatorInterval = function(elem){
var interval = setInterval(function(){
var active = elem.find('.dot.active');
if(active.is('.dot:last-of-type',elem)){
elem.find('.dot').first().click();
}else{
active.next().click();
}
},6000);
interval;
return interval;
};
if($('.rotator').length){
$('.rotator').each(function(){
var self = $(this);
rotatorInterval(self);
self.find('.slide, .dot').on('mouseenter',function(){
console.log('hovered');
clearInterval(interval);
});
});
}
I tried returning the interval from that closure but when I hovered it said interval (the name of the variable I returned) is not defined, so it's like it didn't return it or something.
You just have to actually return the interval reference somewhere
var rotatorInterval = function (elem) {
var interval = setInterval(function () {
var active = elem.find('.dot.active');
if (active.is('.dot:last-of-type', elem)) {
elem.find('.dot').first().click();
} else {
active.next().click();
}
}, 6000);
return interval;
};
if ($('.rotator').length) {
$('.rotator').each(function () {
var self = $(this);
var return_interval = rotatorInterval(self);
self.find('.slide, .dot').on('mouseenter', function () {
clearInterval(return_interval);
});
});
}

Javascript clearInterval in function

I am new to OOP in Javascript or jQuery, I am trying to clear the interval and stop any methods inside the interval, it seems not working with what I did below.
function Timer() {
var sec = $('.timer #second');
this.runTimer = function(_currentime) {
var currentTimeing = parseInt($(_currentime).text());
this.timeInterval = setInterval(function() {
$('.projects li span.second').text(currentTimeing++)
}, 1000);
$("#stop").click(function() {
// clear interval
clearInterval(this.timeInterval);
})
}
}
var play = new Timer();
$("#start").click(function(){
//console.log(this.runTimer())
play.runTimer('#second');
})
You are using this in context of different functions, that's why it's not working fine. Try:
function Timer() {
var sec = $('.timer #second');
this.runTimer = function(_currentime) {
var currentTimeing = parseInt($(_currentime).text()), that = this;
that.timeInterval = setInterval(function(){
$('.projects li span.second').text(currentTimeing ++)
}, 1000);
$("#stop").click(function(){
// clear interval
clearInterval(that.timeInterval);
})
}
}
var play = new Timer();
$("#start").click(function(){
//console.log(this.runTimer())
play.runTimer('#second');
})
I'm simply saving reference to correct this in that variable, so I can later use it to clear interval.
function Timer() {
var sec = $('.timer #second');
var timeinterval; // declare timeinterval variable here
this.runTimer = function(_currentime) {
var currentTimeing = parseInt($(_currentime).text());
timeInterval = setInterval(function(){
$('.projects li span.second').text(currentTimeing ++)
}, 1000);
$("#stop").click(function(){
// clear interval
clearInterval(timeInterval);
})
}
}
var play = new Timer();
$("#start").click(function(){
//console.log(this.runTimer())
play.runTimer('#second');
})

Categories