clearInterval() not working? - javascript

function myFunction(interval) {
var intervalID = window.setInterval(function () {
getdetails();
$('.View').load('alert.php').fadeIn("slow");
}, 3000);
if (interval == 1) {
window.clearInterval(intervalID);
}
}
when I call myFunction with argument 1 then clearInterval() not clear the setInterval().I want setInterval() stop its excution when I call myFunction with argument 1.

The problem is that you are creating a new timer everytime you call the function. Modify it like:
var intervalID = 0;
function myFunction(interval){
if(interval == 1) {
if(intervalID != 0) {
window.clearInterval(intervalID);
intervalID = 0;
}
}
else if(intervalID == 0) { // create only if not existing
intervalID = window.setInterval(function () {
...
});
}
}
Now, the firts time you call it, it will create the timer. Afterwards when you call it with 1 as the argument, it will clear the timer.

Related

Calling functions one from the other and vice versa

I have two timers with two boolean variables and two functions. The first timer is triggered by a click that put true one of the booleans; once the timer reach some conditions this timer is off setting false the boolean and another timer is triggered setting true the second boolean and calling the second timer.
Same once the second timer reach some conditions, the timer is off setting the second boolean false and I try to trigger the first timer setting the first boolean true and calling the first timer, but it dosn't work.
I cannot call the function that is declared underneath the funcion where I do the call.
My code in JavaScript is:
var active=false;
var activeBreak=false;
...
function breakDown(){
if(activeBreak){
...
if(some conditions){
active=true;
activeBreak=false;
countDown();// **This call doesn't work.Black in jsbin**
}
}
}
function countDown(){
if(active){
...
if(someConditions){
active=false;
activeBreak=true;
breakDown();// *This call works. Blue in jsbin*
}
}
}
...
$("#circle").click(function(){
active=true;
countDown(); // *This call works*/
});
Try
$(document).ready(function(){
/* Global variables */
var state = 'STOPPED';
var timeSession = 1;
var timeBreak = 1;
var timeout = 0;
function resetTimer(time) {
timeout = (new Date()).getTime() + (time*60*1000);
}
function changeState() {
if (state === 'SESSION') {
state = 'BREAK';
resetTimer(timeBreak);
} else if (state === 'BREAK' || state === 'STOPPED') {
state = 'SESSION';
resetTimer(timeSession);
}
$('#text').text(state);
}
/* Function for the countdown ****************************/
function countDown (){
if (state !== 'STOPPED') {
var time = (new Date()).getTime();
if (timeout <= time) {
changeState();
return;
}
var s = Math.floor((timeout - time) / 1000);
var m = Math.floor(s / 60);
s = s - m*60;
$('#timer').text(""+((timeout - time) / 1000)+" "+timeout+" "+m+":"+("0"+s).substr(-2));
}
setTimeout(countDown, 1000);
}
/*****Click Break ********************/
$("#breakMinus").click(function(){
if (timeBreak > 1) {
--timeBreak;
}
$("#breakContent").html(timeBreak);
});
$("#breakPlus").click(function(){
++timeBreak;
$("#breakContent").html(timeBreak);
});
/******Click Session Length****************/
$("#seMinus").click(function(){
if (timeSession > 1) {
--timeSession;
}
$("#seContent").html(timeSession);
});
$("#sePlus").click(function(){
++timeSession;
$("#seContent").html(timeSession);
});
/***********Click circle****************/
$("#circle").click(changeState);
setTimeout(countDown, 1000);
$('#text').text(state);
});

How to write a test case for a setInterval() function

I have a timer and assume a specific function will be executed when the counter is counting to 3.
var a_interval_function = function(){
var counter = 1;
var interval = setInterval(function(){
if(counter === 5){
clearInterval(interval);
}
// run the function when the counter is 3
if(counter === 3){
a_function_should_be_runned();
}
counter++;
}, 500);
return interval;
}
However, I don't know how to establish a valid test case for testing the counter as well as the timing when the function is executed. Does anyone know how to do it? Something like the following:
// and some test case like this
it('a timer test', function(done){
var interval = a_interval_function();
expect(a_function_should_be_runned.state).to.equal({
name: 'runned',
counter: 3,
time: 300,
});
});
Thanks.
Perhaps you can use sinon.useFakeTimers().
For example:
var sinon = require('sinon');
var expect = require('chai').expect;
var a_function_should_be_runned = sinon.spy();
var a_interval_function = function(){
var counter = 1;
var interval = setInterval(function(){
if(counter === 5){
clearInterval(interval);
}
// run the function when the counter is 3
if(counter === 3){
a_function_should_be_runned();
}
counter++;
}, 500);
return interval;
}
describe('timer tests', function() {
before(function() {
this.clock = sinon.useFakeTimers();
});
after(function() {
this.clock.restore();
});
it('a timer test', function() {
var interval = a_interval_function();
// At time 0, we don't expect the function to have been called.
expect(a_function_should_be_runned.called).to.be.false;
// Advance clock 500ms.
this.clock.tick(500);
expect(a_function_should_be_runned.called).to.be.false;
// Advance clock again (1s since start)
this.clock.tick(500);
expect(a_function_should_be_runned.called).to.be.false;
// Advance clock again (1.5s since start). This should
// trigger the call to `a_function_should_be_runned`.
this.clock.tick(500);
expect(a_function_should_be_runned.called).to.be.true;
});
});
Here is my naïve approach:
it('a timer test', function(done){
var interval = a_interval_function();
setTimeout(function () {
expect(a_function_should_be_runned.state).to.equal({
name: 'runned',
counter: 3,
time: 300,
});
done();
}, 3.5 * 500);
});
What you do here is basically waiting 1.75s and expecting that the a_function_should_be_runned function has been executed on timeout. Then you call the expect function in order to check your assertion. Finally you call done(). Note that done() is called inside the setTimeout callback function. If you don't call done() your test just times out.
Easiest way to check if the code / function gets executed is just by putting in an alert or console.log, so you have visual confirmation of what is happening. Also you can console.log the counter in your interval so you can see the counter going up.
grammar nazies in the house....
[edit]
var a_interval_function = function(){
var counter = 1;
var interval = setInterval(function(){
if(counter === 5){
clearInterval(interval);
}
// run the function when the counter is 3
if(counter === 3 && testFunction()){
a_function_should_be_runned();
}
counter++;
}, 500);
return interval;
}
function testFunction(){
if(KeyboardNinja == 'awesome'){
return true;
} else {
return false;
}
}
Your test will never fail :P

jQuery reset setInterval timer

My Jquery:
function myTimer() {
var sec = 15
var timer = setInterval(function() {
$('#timer').text(sec--);
if (sec == -1) {
clearInterval(timer);
alert('done');
}
} , 1000);
}
$("#knap").click(function() {
myTimer();
});
$("#reset").click(function() {
// set timer to 15 sec again..
});
I want the timer to be reset when clicked on #reset.
You need to leave your "timer" variable in a scope that is available the next time you call the myTimer function so you can clear the existing interval and reset it with a new interval. Try:
var timer;
functionn myTimer() {
var sec = 15
clearInterval(timer);
timer = setInterval(function() {
$('#timer').text(sec--);
if (sec == -1) {
clearInterval(timer);
alert('done');
}
} , 1000);
}
$("#knap").click(function() {
myTimer();
});
$("#reset").click(function() {
myTimer();
});
or you could do something along these lines:
var myTimer = function(){
var that = this,
time = 15,
timer;
that.set = function() {
console.log('setting up timer');
timer = setInterval(function(){
console.log('running time: ' + time);
},1000);
}
that.reset = function(){
console.log('clearing timer');
clearInterval(timer);
}
return that;
}();
and run when you need to:
myTimer.set();
myTimer.reset();
Clear the timer every time it's initalized, that way all you have to do is call the function again to reset the timer :
var timer;
function myTimer(sec) {
if (timer) clearInterval(timer);
timer = setInterval(function() {
$('#timer').text(sec--);
if (sec == -1) {
clearInterval(timer);
alert('done');
}
}, 1000);
}
$("#knap, #reset").click(function() {
myTimer(15);
});
FIDDLE
You could re-write your myTimer() function like so:
function myTimer() {
var sec, timer = null;
myTimer = function() {
sec = 15;
clearInterval( timer );
timer = setInterval(function() {
$('#timer').text(sec--);
if (sec == -1) {
clearInterval(timer);
alert('done');
}
} , 1000);
};
myTimer();
}
Now, whenever you call myTimer(), the setInterval gets reset.
Here's an approach that is more in tune with the way JS was designed (as a functional language for those who still don't know). Rather than relying on a global variable, use a closure:
$("#knap").click(function start()//named callback to bind && unbind:
{
$(this).unbind('click');//no need to start when started
$("#reset").unbind('click').click((function(timer)
{//timer is in scope thanks to closure
return function()
{//resets timer
clearInterval(timer);
timer = null;
$('#knap').click(start);//bind the start again
//alternatively, you could change the start button to a reset button on click and vice versa
}
})(setInterval((function(sec)
{
return function()
{
$('#timer').text(sec--);
if (sec === -1)
{
$('#reset').click();//stops interval
$('#reset').unbind('click');//no more need for the event
alert('done');
}//here's the interval counter: 15, passed as argument to closure
})(15),1000)));//set interval returns timer id, passed as argument to closure
});
Now I will admit this is rather messy (and untested) but this way there reset event is only available when it's necessary, and you're not using any globals. But crucially, this is where JS's power lies: functions as 1st class objects, passing them as arguments and return values... just go function-crazy :)
I've set up a working Fiddle, too
You could also use a jQuery timer plugin, then you don't need to pass around the Variable.
Plugin: http://archive.plugins.jquery.com/project/timers
Example for the plugin: http://blog.agrafix.net/2011/10/javascript-timers-mit-jquery/

setinterval method not working

I have a button which triggers the function inside set interval every 1 sec.
The value of the button changes to stop. When I hit stop I call the clearinterval method.
For some reason the clear interval method is not working.
This is my input
<input id="trigger" type="button" value="start"/>
my js function
$(function() {
$('#trigger').click(function() {
var timerId = 0;
var trigger = $('#trigger').val();
if(trigger == 'start') {
timerId = setInterval(function() {
$('#trigger').val('stop');
main();
}, 1000);
} else if(trigger == 'stop') {
clearInterval(timerId);
$('#trigger').val('start');
}
});
});
You have timerId is defined to be local to the scope of click(), so when you run it the second time (in the stop event) it will be 0 again. Try this
var timerId = 0;
$(function() {
$('#trigger').click(function() {
var trigger = $('#trigger').val();
if(trigger == 'start') {
timerId = setInterval(function() {
$('#trigger').val('stop');
main();
}, 1000);
} else if(trigger == 'stop') {
clearInterval(timerId);
$('#trigger').val('start');
}
});
});
You are re-initialising the timerId every time #trigger is clicked. Move the var timerId = 0; outside the click function

setInterval - javascript reset

I am using setInterval in a loop. Once the condition has been met (aa=bb) and interval cleared, is it possible to reset interval?
var interval = setInterval(function()
{
if( aa == bb)
{
clearInterval(interval);
}
} , 10000);
If you make the code a function like this, you can call it anytime to start it over.
function startInterval() {
var interval = setInterval(function() {
if( aa == bb) {
clearInterval(interval);
}
}, 10000);
}
startInterval();

Categories

Resources