clearTimeout Function not working properly on dialog when open - javascript

Here i attached my code. am clear the time out function when dialog is open.but its not working properly.When i open my dialog the count down decreasing from 20 but in between 20 seconds if i close and open the dialog , the timing is collapsing each other.
function(){
var time =20;
flag = false;
clearTimeout(startTimer);
startTimer = function(){
if(!flag){
var finTime = time - 1;
time = finTime;
setTimeout(startTimer,1000);
if(time==0){
flag = true; }
$("#input").text(time);
} else {
clearTimeout(startTimer,1000);
}
};
setTimeout(startTimer,1000);
};
I have tried this code also
dialogOpen = function(){
$("#dialog").dialog('open');
startTimer();
stopTimer();
}
startTimer = function() {
time = 20;
flag = false;
setTimeout(startTime, 1000);
};
stopTimer = function() {
flag = true;
time = 0;
clearTimeout(startTime);
};
startTime = function(){
if(!flag){
var finTime = time - 1;
time = finTime;
setTimeout(startTime,1000);
if(time==0){
flag = true;
}
$("#input").text(time);
} else {
clearTimeout(Time);
}
};

You have to assign setTimeout to a variable
var timer;
timer = setTimeout(startTimer,1000);
and you can clear the setTimeout using clearTimeout by passing the variable.
clearTimeout(timer);

To call clearTimeout() you want to pass in the intervalVariable that was returned by setTimeout(), not the function, so it would look like:
var intervalVariable = setTimeout(startTimer,1000);
clearTimeout(intervalVariable);
It's best to thing of intervalVariable as the ID for the timeout that is then used by the browser to cancel it.
Set a global variable before your startTimer function, then set it to the return of setTimeout() and use it in place of startTimer in clearTimeout().

Related

Calling a function onclick start and onclick stop

I am using the below functions to start and stop spin.Basically I am trying to add an Autospin button and tried below approach but its not working.Start function is working but stop not working.
var nIntervId;
this._onAutoSpin = function(){
s_oGame.onSpin();
nIntervId = setInterval(this._onAutoSpin, 10 * 1000);
};
this._offAutoSpin = function(){
clearInterval(nIntervId);
};
The issue is because you're recursively starting a new interval every time it fires, therefore you only stop the latest timer, not the previous.
To fix this change your logic so that there is no possible recursion and there is only ever one interval running:
function Foo() {
var nIntervId;
this._onAutoSpin = function() {
nIntervId = setInterval(this._doAutoSpin, 1 * 1000); // modified for demo
}
this._doAutoSpin = function() {
console.log('spinning...');
};
this._offAutoSpin = function() {
console.log('stopped');
clearInterval(nIntervId);
};
}
var foo = new Foo();
foo._onAutoSpin();
setTimeout(foo._offAutoSpin, 5000); // stop after 5 seconds
If you want to do this recursively then you need to use setTimeout(). You also need to cache the this reference so that it is maintained within the successive calls:
function Foo() {
var nIntervId;
this._onAutoSpin = function() {
var _this = this;
console.log('spinning...');
nIntervId = setTimeout(function() {
_this._onAutoSpin();
}, 1 * 1000); // modified for demo
}
this._offAutoSpin = function() {
console.log('stopped');
clearInterval(nIntervId);
};
}
var foo = new Foo();
foo._onAutoSpin();
setTimeout(foo._offAutoSpin, 5000); // stop after 5 seconds
try to use setTimeout instead of setInterval because setInterval creates a new timer every time without destroying the last one.
var nIntervId;
this._onAutoSpin = function(){
s_oGame.onSpin();
nIntervId = setTimeout(this._onAutoSpin, 10 * 1000);
};
this._offAutoSpin = function(){
clearTimeout(nIntervId);
};

How to stop a function in another function

How i can stop a function in another function?
For example:
var snow = function(){
var interval = setInterval( function(){
alert('letItSnow')
}, 1000);
};
snow();
clearInterval(snow.interval) - exception
In javascript, access scopes are limited via function declarations, so your locally declared variables won't be accessible outside, hence you must return it or set it to a global variable (variable available in parent scope)
you need to make a slight adjustment to your function, do it like this:
var snow = function(){
return setInterval(function(){
alert('letItSnow');
}, 1000);
};
var interval = snow();
//on some event -- clearInterval(interval)
you can also make the setTimeout and its returned id a property to the function which would be available on all of its instances i.e.
var snowClass = function(){
this.init = function(msg){
this.interval = setInterval(function(){alert(msg)},1000);
}
}
var snowObj = new snowClass();
snowObj.init('Let it snow');
//on some event -- clearInterval(snowObj.interval)
you referring to snow.interval which assumed to be property of snow object. but in your code interval is just local variable. instead you might want to define interval in the global scope so it will be accessible globally http://www.w3schools.com/js/js_scope.asp
var interval, snow = function(){
interval = setInterval( function(){
console.log('letItSnow')
}, 1000);
};
snow();
clearInterval(interval);
If I understand the question correctly, you want to stop the interval outside of the snow function.
You can declare the interval variable outside of the snow function in order to use it (to clear the interval) outside of the snow function.
var interval;
var snow = function(){
interval = setInterval(
function(){
alert('letItSnow')
},
1000
);
};
snow();
clearInterval(interval);
try this in your code
var timeout1 = {};
var timeout2 = {};
function function1(){
//codes
if(timeout2){
clearTimeout(timeout2);
}
timeout1 = setTimeout("function1()",5000);
}
function function2(){
//codes
if(timeout1){
clearTimeout(timeout1);
}
timeout2 = setTimeout("function2()",5000);
}

How to disable a function when time passed?

I'm trying to disable 2 functions when a certain time period is reached and enable the other 2 after that time period. So the second 2 functions would have to be disabled to begin with.
I was thinking of using the following code to wrap around the functions:
Code:
var startTime = new Date().getTime();
var interval = setInterval(function(){
if(new Date().getTime() - startTime > 5000){
clearInterval(interval);
return;
}
function 1() {}
$(function 2() {});
}, 1000);
function 3() {}
$(function 4() {});
Can you help?
If you want to control whether functions do something or not, based on how much time has elapsed, it would probably be easier to set a flag after the interval you need, and then have your functions check that flag to decide if they are going to do something:
var timedOut = false;
setTimeout(function () {
timedOut = true;
}, 5000);
function one() {
if (!timedOut) {
// do something
}
}
function two() {
if (!timedOut) {
// do something
}
}
function three() {
if (timedOut) {
// do something
}
}
function four() {
if (timedOut) {
// do something
}
}
This should get you started; I've simply redefined the original func1/func2 functions after a set time (5 seconds, as your example uses). This could do any number of things (such as remove the function definition altogether).
(function(document,window,undefined){
// Used simply to show output to the window.
var db = document.getElementById('db');
// Here we define the initial state of our two functions.
// Nothing magical here, just outputting a description.
window.func1 = function(){
db.innerHTML += 'Hello from original func1\r\n';
}
window.func2 = function(){
db.innerHTML += 'Hello from original func2\r\n';
}
// Here we keep the same format you used (using the Date to
// define when one's been deprecated over the other).
var startTime = new Date().getTime(),
interval = setInterval(function(){
var currentTime = new Date().getTime(),
delta = currentTime - startTime;
if (delta > 5000){
// In here, now that the specified amount of time has
// elapsed, we redefine the meaning of the two original
// functions. We could also simply remove them.
window.func1 = function(){
db.innerHTML += 'Hello from NEW func1\r\n';
}
window.func2 = function(){
db.innerHTML += 'Hello from NEW func2\r\n';
}
clearInterval(interval);
}
}, 1000);
})(document,window);
// This is here just to show you how one definition is changed
// in place of another.
setInterval(function(){
func1();
func2();
}, 1000);
<pre id="db"></pre>
If you mean 'disabling' the functions after certain amount of seconds then this should do the trick.
var secondsLimit = 10,
a = 0,
b = setInterval(function () { a += 1; }, 1000 });
function A() {
if (a > secondsLimit) {
return;
}
// do stuff
}
You can change the functions if you call them e.g. by a global variable scope.
In the following example based on your code, the functions switch after 4 seconds.
var function1 = function() {
console.log("function 1 active");
};
var function2 = function() {
console.log("function 2 active")
}
var startTime = new Date().getTime();
setTimeout(function() {
function1 = function() {
console.log("now function 3 is active instead of function 1");
}
function2 = function() {
console.log("now function 4 is active instead of function 2");
}
}, 4000);
//the following code is just for testing reasons
var interval = setInterval(function() {
function1();
function2();
}, 1000)

how do I start and stop a timer from an options page

Right now i have this 1 minute timer in my background page that runs forever i would like to be able to start and stop it from an options page.
chrome.browserAction.setBadgeBackgroundColor({color:[0, 0, 0, 255]});
var i = 1;
window.setInterval(function(timer) {
chrome.browserAction.setBadgeText({text:String(i)});
i++;
}, 60000);
setInterval() method of the Window object schedules a function to be invoked repeatedly at intervals of the specified number of milliseconds. setInterval() returns an opaque value that can be passed to clearInterval() to cancel any future invocations of the scheduled function. Read more about How Javascript Timers work. With that you can write something like this:
My.Controller = {};
(function() {
var interval = 10;
var timer = null;
function init (param) {
// initialisations if any
}
// Override the default interval of 10 seconds by passing new interval
function startAction (param, tInterval) {
// Set a timer
var ti = (!tInterval) ? interval : tInterval;
timer = setInterval(My.Controller.action, ti * 2000);
}
function action () {
// Logic here
}
function stopAction () { clearInterval(timer); }
var c = My.Controller;
c.init = init;
c.startAction = startAction;
c.stopAction = stopAction;
})(); // end Controller
Now you can say My.Controller.startAction() to start the timer and and My.Controller.stopAction() to stop.
Read and explore about namespaces in JavaScript.
Hope this helps.

Javascript, AJAX, Extend PHP Session Timeout, Bank Timeout

Greetings,
I have the following JS code:
var reloadTimer = function (options) {
var seconds = options.seconds || 0,
logoutURL = options.logoutURL,
message = options.message;
this.start = function () {
setTimeout(function (){
if ( confirm(message) ) {
// RESET TIMER HERE
$.get("renewSession.php");
} else {
window.location.href = logoutURL;
}
}, seconds * 1000);
}
return this;
};
And I would like to have the timer reset where I have the comment for RESET TIMER HERE. I have tried a few different things to no avail. Also the code calling this block is the following:
var timer = reloadTimer({ seconds:20, logoutURL: 'logout.php',
message:'Do you want to stay logged in?'});
timer.start();
The code may look familiar as I found it on SO :-)
Thanks!
First of all, you need to use the new operator in var timer = new reloadTimer, and also reloadTimer should be capitalized into ReloadTimer to signify that it needs to be used with new.
The reason why you need new is because the function references this and when used without new this will be the global scope instead of the instance it self.
To reset a timer you just call window.clearTimeout with the timers reference as the parameter
var timer = window.setTimeout(....
...
window.clearTimeout(timer);
UPDATE
By RESET do you actally mean to restart the timer?
If so, just use setInterval instead of setTimeout
UPDATE 2
And here is a slightly better approach (if you still want to use such a class to encapsulate something so trivial)
var ReloadTimer = function(options){
var seconds = options.seconds || 0, logoutURL = options.logoutURL, message = options.message;
var timer;
return {
start: function(){
timer = setInterval(function(){
if (confirm(message)) {
$.get("renewSession.php");
}
else {
clearInterval(timer);
window.location.href = logoutURL;
}
}, seconds * 1000);
}
};
};
var myTimer = new ReloadTimer({
seconds: 20,
logoutURL: 'logout.php',
message: 'Do you want to stay logged in?'
});
myTimer.start();
You could execute the function again with the same parameters?

Categories

Resources