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.
Related
var time = 1000;
var point = 0;
function interval() { timeout = setTimeout(increment, time);}
function increment(){point += 1;document.getElementById("pul").value = point;interval();}
time2 = 3000;
function fermafatica() {setInterval(ferma, time2);}
function ferma(){clearTimeout(timeout)}
i need to stop the interval() function or the setTimeout in interval() for only 1000ms and then to keep it working
Are you asking about how to clear a timeout after X seconds? I would consider just having a static variable (lets just call it X) count up within the repeating function, and if the function repeats every 10ms, and you want it to run for 1000ms, then when x==100, clear the timeout.
You could try:
setTimeout(function() {
z();
// Do anything else here
}, 1000);
The setTimeout function, runs the given function after a set amount of time. This will call the z() function, which clears your timeout, after the supplied time of 1000ms.
EDIT: Everything: See below
var time = 1000;
var point = 0;
function interval() { timeout = setTimeout(increment, time);}
function increment(){point += 1;document.getElementById("pul").value = point;interval();}
time2 = 3000;
function fermafatica() {setInterval(ferma, time2);}
function ferma(){clearTimeout(timeout)}
Change function fermafatica() {setInterval(ferma, time);}
to function fermafatica() {setTimeout(ferma, time);}
ok.... i "avoid" the problem.... i need to stop the setTimeout for 1000ms and then let it works normally... i tried so... instead of pausing the setTimeout I put another time var.
var time = 1000;
var timecache = 1000;
fatica = 3000;
sudore = 3000;
function interval() { timeout = setTimeout(increment, time);} //here setTimeout uses var time//
function increment(){console.log(time);point += 1;document.getElementById("pul").value = point;interval();}
function fermafatica() {time = timecache;setInterval(ferma, fatica);} //here the function equals time to timecache so vas time is always 1000ms//
function ferma(){time = 10000; setTimeout(fermafatica, sudore);} // then here I transformed the time in 10000 so the first function will take 10000 instead of 1000 in setTimeout//
//plus i put a setTimeout to recall function fermafatica() that reset the time to 1000//
this i what i want... I avoid the problem and found another way to do that... but it works...
Here I have a piece of code that auto-executes every 2 seconds. However, the time it takes to execute function roll() varies due to the Internet connection's peaks and bottoms. I'm trying to make the function roll() execute itself automatically every 2 seconds, but the code must wait till the function is fully executed before proceeding and auto-executing again.
P.S. Any suggestions of a better title for this question would be appreciated.
var init = 0.01
var start = init
var $odds = $("#oddsOverUnder")
var $button = $("#roll")
var $bet = $("#bet")
function roll() {
$bet.val(start)
$button.click()
setTimeout(function() {
var tr = document.querySelector("#myBetsTable tr:nth-child(2)")
var cls = tr.getAttribute('class')
if (cls === 'success'){
start = init
$bet.val(start)}
else{
start = start * 2
$bet.val(start)
$odds.click()}
$button.click();
setTimeout(function() {
$button.click();
},1000);
},1000);
}
setInterval(roll, 2000)
Don't use setInterval. It will try to call a function after the elapsed time regardless whether it's finished or not. setTimeout is better, as you can control when it gets called. And you quite normally just call it at the end of a function (where it calls itself).
E.g.
function draw() {
// Some drawing here...
setTimeout(draw, 50);
}
So, when you call draw() above, it will do its operations, then wait 50 ms and then call itself again, repeatedly.
See here for further details on the difference.
I added setTimeout to the roll function and called it at the end.
var init = 0.01
var start = init
var $odds = $("#oddsOverUnder")
var $button = $("#roll")
var $bet = $("#bet")
function roll() {
setTimeout(roll, 2000)
$bet.val(start)
$button.click()
setTimeout(function() {
var tr = document.querySelector("#myBetsTable tr:nth-child(2)")
var cls = tr.getAttribute('class')
if (cls === 'success'){
start = init
$bet.val(start)}
else{
start = start * 2
$bet.val(start)
$odds.click()}
$button.click();
setTimeout(function() {
$button.click();
},1000);
},1000);
}
roll()
The best would be to do soemething like this:
function roll() {
var time = Date.now();
//your stuff goes here
setInterval(roll, Math.max(2000 - (Date.now() - time)), 1);
}
This tries to optimize tge amount of time between calls, so if the function took 1.5 seconds, then it will fire after 0.5 seconds.
We have started a timer with the following code. Is it possible to make window.setInterval method fail, if another timer is active on the method passed to the window.setInterval method?
GInterValId = window.setInterval("AutoRefresh()",parseInt(GRefreshInterval));
what you do is set up a system for this. Create an object that handle all your Timers:
var Timer = function () {
var currentTimer;
this.setTimer = function (func,time) {
if (currentTimer) {
alert("one timer already set");
}else {
currentTimer = setInterval(func,time);
}
}
this.stopTimer = function () {
clearInterval(currentTimer);
currentTimer = null;
}
}
Now you can use this code:
function doSomething() {...} // function example
function doSomethingElse() {...} // function example
var MyTimer = new Timer();
MyTimer.setTimer(doSomething,1000); // this will run
MyTimer.setTimer(doSomethingElse,1000); // this will not run
The second one will not run because the other one is active.
to make it work you have clear the first one.
MyTimer.stopTimer(); // will clear the current timer then you can run another one
MyTimer.setTimer(doSomethingElse,1000); // will run perfectly
If you keep track of the result result from window.setInterval(), you can stop the previous interval timer at any point.
var GInterValId = setInterval(AutoRefresh, parseInt(GRefreshInterval));
Then, when you want to reset it:
if (GInterValId) {
clearInterval(GInterValId);
}
GInterValId = setInterval(AutoRefresh, parseInt(GRefreshInterval));
Also note that I'm not passing a string to setInterval, but an actual JS function reference.
Or, if you just want to prevent another interval getting set:
var GInterValId = null; // initialize
// then, when you want to set it, check to see if it's already been set
if (GInterValId) {
GInterValId = setInterval(AutoRefresh, parseInt(GRefreshInterval));
}
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?
The window.setTimeout (and related setInterval) function in Javascript allows you to schedule a function to be executed sometime in the future:
id = setTimeout(function, delay);
where "delay" is the number of milliseconds into the future at which you want to have the function called. Before this time elapses, you can cancel the timer using:
clearTimeout(id);
What I want is to update the timer. I want to be able to advance or retard a timer so that the function gets called x milliseconds sooner or later than originally scheduled.
If there were a getTimeout method, you could do something like:
originally_scheduled_time = getTimeout(id);
updateTimeout(id, originally_schedule_time + new_delay); // change the time
but as far as I can tell there's nothing like getTimeout or any way to update an existing timer.
Is there a way to access the list of scheduled alarms and modify them?
Is there a better approach?
thanks!
If you really want this sort of functionality, you're going to need to write it yourself.
You could create a wrapper for the setTimeout call, that will return an object you can use to "postpone" the timer:
function setAdvancedTimer(f, delay) {
var obj = {
firetime: delay + (+new Date()), // the extra + turns the date into an int
called: false,
canceled: false,
callback: f
};
// this function will set obj.called, and then call the function whenever
// the timeout eventually fires.
var callfunc = function() { obj.called = true; f(); };
// calling .extend(1000) will add 1000ms to the time and reset the timeout.
// also, calling .extend(-1000) will remove 1000ms, setting timer to 0ms if needed
obj.extend = function(ms) {
// break early if it already fired
if (obj.called || obj.canceled) return false;
// clear old timer, calculate new timer
clearTimeout(obj.timeout);
obj.firetime += ms;
var newDelay = obj.firetime - new Date(); // figure out new ms
if (newDelay < 0) newDelay = 0;
obj.timeout = setTimeout(callfunc, newDelay);
return obj;
};
// Cancel the timer...
obj.cancel = function() {
obj.canceled = true;
clearTimeout(obj.timeout);
};
// call the initial timer...
obj.timeout = setTimeout(callfunc, delay);
// return our object with the helper functions....
return obj;
}
var d = +new Date();
var timer = setAdvancedTimer(function() { alert('test'+ (+new Date() - d)); }, 1000);
timer.extend(1000);
// should alert about 2000ms later
I believe not. A better approach might be to write your own wrapper which stores your timers (func-ref, delay, and timestamp). That way you can pretend to update a timer by clearing it and calculate a copy with an updated delay.
Another wrapper:
function SpecialTimeout(fn, ms) {
this.ms = ms;
this.fn = fn;
this.timer = null;
this.init();
}
SpecialTimeout.prototype.init = function() {
this.cancel();
this.timer = setTimeout(this.fn, this.ms);
return this;
};
SpecialTimeout.prototype.change = function(ms) {
this.ms += ms;
this.init();
return this;
};
SpecialTimeout.prototype.cancel = function() {
if ( this.timer !== null ) {
clearTimeout(this.timer);
this.timer = null;
}
return this;
};
Usage:
var myTimer = new SpecialTimeout(function(){/*...*/}, 10000);
myTimer.change(-5000); // Retard by five seconds
myTimer.change(5000); // Extend by five seconds
myTimer.cancel(); // Cancel
myTimer.init(); // Restart
myTimer.change(1000).init(); // Chain!
It may be not exactly what you want, but take a look anyway, maybe you can use it to your benefit.
There is a great solution written by my ex-coworker that can create special handler functions that can stop and start timeouts when required. It is most widely used when you need to create a small delay for hover events. Like when you want to hide a mouseover menu not exactly at the time when a mouse leaves it, but a few milliseconds later. But if a mouse comes back, you need to cancel the timeout.
The solution is a function called getDelayedHandlers. For example you have a function that shows and hides a menu
function handleMenu(show) {
if (show) {
// This part shows the menu
} else {
// This part hides the menu
}
}
You can then create delayed handlers for it by doing so:
var handlers = handleMenu.getDelayedHandlers({
in: 200, // 'in' timeout
out: 300, // 'out' timeout
});
handlers becomes an object that contains two handler functions that when being called cancel the other one's timeout.
var element = $('menu_element');
element.observe('mouseover', handlers.over);
element.observe('mouseout', handlers.out);
P.S. For this solution to work you need to extend the Function object with the curry function, which is automatically done in Prototype.
One possibility can be like this:
if (this condition true)
{
setTimeout(function, 5000);
}
elseif (this condition true)
{
setTimeout(function, 10000);
}
else
{
setTimeout(function, 1000);
}
It's up to your how you construct your conditions or the logic. thanks