i am opening a page on the chrome by using F12, and i realize it do have a timer inside the source code, however, the timer started on the page load and it does not store the timer as a variable, what the source code use is
self.setTimeout("OnReload()", 60000);
so if i am intend to using window.clearTimeout(timer);
Since it is not store as a variable, i am not able to using this method to clear the timeout variable, may i ask am i able to clear this timeout???
As you cannot disable the timer, why not just overload the function i.e.
function OnReload() { }
So that it does nowt.
the answer is i key in self.clearTimeOut(0);
and it work
Related
The title sums up the weird problem I am having. I declare a global variable, execute a setInterval function which modifies that variable and deppending on the duration of the interval, the variable will look modified or not.
To be more clear, this simple background file code illustrates the situation:
var TabId=0;
var target= "https://google.com";
function start() {
chrome.tabs.create({url: target}, function(tab) {TabId=tab.id;});
setInterval(Repeat, 30*1000); //repeat every 30 seconds
}
function Repeat(){
chrome.tabs.remove(TabId);
chrome.tabs.create({url: target}, function(tab) {TabId=tab.id;});
}
chrome.browserAction.onClicked.addListener(start);
I am surprised that for "short" intervals such as 10 seconds, the extension works just fine, but for 30 seconds, for example, it fails. It does nothing after the specified time is elapsed, and if you check in the console the value of TabId, it is still 0. It looks as if the code line
TabId=tab.id;
has never been executed, which is impossible because the tab has been created, right?
But there is something more: if you open the console for the background page before even firing the onClicked event, it seems to run ok as expected!
Can anybody help me understand what is going on here?
At first I thought it could have to do with the variable scope, but it doesn't make sense because for shorter intervals it works perfectly.
Regards.
My bad.
In my manifest file I had set "persistent" to false. This property enables you to work with an event page instead of a background page.
Event pages are loaded only when they are needed. When the event page is not actively doing something, it is unloaded, freeing memory and other system resources.
So, after a while waiting for the interval to complete, the TabId is erased.
It was driving me crazy, but this morning I woke up with a hint for the solution.
I use a simple jquery command in the Google Chrome console to manage my site. Basically, I have to approve a number of new requests every day, so I use:
$('.approve').click();
where 'approve' is the class name of the button that needs to get clicked. This saves me hours. However, this crashes my browser every time, and sometimes doesn't work, mainly because of the resource taxing it put on my laptop. I was looking for a way to slow down the actions of the function. I tried...
$('.approve').click().delay(1000);
to try and slow it down by 1 second between button clicks. This didn't seem to work (it ran without errors but I don't think it slowed down the clicking.
Any ideas?
Edit:
Someone pointed out that this may be a duplicate of another question. The reason it isn't is that the other top answer focuses on using JS to define a function that uses setTimeout(), where I am looking for a native jquery method of doing it. I understand jquery is written in JS, but because I'm using it in a command console, I don't have the luxury of multiple lines of coding space.
Can anyone also tell me why the above function wouldn't work? It seems like it should, based on my research.
Thank you in advance.
Wait 1 second between each click:
You will need to iterate over each .approve-button, then trigger the click event for each button with a second in between: (setTimeout)
$('.approve').each(function(index) {
var $approve = $(this);
setTimeout(function() {
// Simulation click event
$approve.trigger('click');
// 0, 1, 2, 3, ... times 1000 to bring delay to miliseconds
}, index * 1000);
});
One liner (For IE9+):
$(".approve").each(function(c){setTimeout(function(c){c.click()},1e3*c,$(this))});
One liner:
$(".approve").each(function(e){var i=$(this);setTimeout(function(){i.click()},1e3*e)});
You can add a delay on the function click like so
$(".approve").click(function(){
setTimeout(function(){
// Do something
}, 1000);
});
If you want to exectue your function once, use setTimeout()
$(".approve").click(function(){
setTimeout(function(){
}, 1000);
});
If you want to exectue it every second, use setInterval()
when click you have to run a function that will execute setTimeout function
$('.approve').click(function(){
setTimeout(function(){
// here some code u want to execute after 5 sec //
}, 5000);
});
In my android app, developing by titanium studio 3.1.3, I have tab group where in the last(fifth tab) I am using button to open a new page
-> new page contains switch, if switch is on I am calling a method like
function locationSetEnable() {
Ti.App.Properties.setString('getLocation', 'YES');
getlocation_coords();
timer = setInterval(getlocation_coords, 20000);
}
so it is calling getlocation_coords method in every 20 seconds, and If switch is off I am calling other method,
function locationSetDisable() {
Titanium.Geolocation.removeEventListener('location', locationCallback);
clearInterval(timer);
Ti.App.Properties.setString('getLocation', 'NO');
}
so, here clear interval is working properly the method getlocation_coords calling is stopped.
it is happening only I am on the same screen.
My issue is :
If my switch is on, and I moved into any other screen/tab and coming back to same screen and now I am going off my switch this time the clearInterval is not working, it is calling autometically the getlocation_coords method is calling continiously, how do I resolve this issue?
Thanks in advance
try to make your "timer" variable global. Like you can create var timer = null; only once in app.js. Now you can access it in all .js files.
I want to stop a script from executing, similar to what the Esc key does in Firefox. It stops all Javascript from running on that page as well as all gif animations.
Is there a function I could call which would stop everything?
Depending on how the offending module is organized, perhaps you can monkey-patch it without having to change its source code.
For example, if the annoying polling function is global or namespaced you can try to replace it with a useless stub:
//save the old version of the function, in case
//we need to restore it afterwards
var nasty_function = His.Namespaced.Evil.func;
//put our own stub in place
His.Namespaced.Evil.func = function(what, args, it , should, receive){
return somthing_that_signals_a_failed_poll;
}
No, there is nothing like that. And there's also no real reason for it: you write the code, you can make it stop doing things if you want to.
Plus: if there were such a function that stopped all JS activity... how would you make it start up again?
I have a function called save(), this function gathers up all the inputs on the page, and performs an AJAX call to the server to save the state of the user's work.
save() is currently called when a user clicks the save button, or performs some other action which requires us to have the most current state on the server (generate a document from the page for example).
I am adding in the ability to auto save the user's work every so often. First I would like to prevent an AutoSave and a User generated save from running at the same time. So we have the following code (I am cutting most of the code and this is not a 1:1 but should be enough to get the idea across):
var isSaving=false;
var timeoutId;
var timeoutInterval=300000;
function save(showMsg)
{
//Don't save if we are already saving.
if (isSaving)
{
return;
}
isSaving=true;
//disables the autoSave timer so if we are saving via some other method
//we won't kick off the timer.
disableAutoSave();
if (showMsg) { //show a saving popup}
params=CollectParams();
PerformCallBack(params,endSave,endSaveError);
}
function endSave()
{
isSaving=false;
//hides popup if it's visible
//Turns auto saving back on so we save x milliseconds after the last save.
enableAutoSave();
}
function endSaveError()
{
alert("Ooops");
endSave();
}
function enableAutoSave()
{
timeoutId=setTimeOut(function(){save(false);},timeoutInterval);
}
function disableAutoSave()
{
cancelTimeOut(timeoutId);
}
My question is if this code is safe? Do the major browsers allow only a single thread to execute at a time?
One thought I had is it would be worse for the user to click save and get no response because we are autosaving (And I know how to modify the code to handle this). Anyone see any other issues here?
JavaScript in browsers is single threaded. You will only ever be in one function at any point in time. Functions will complete before the next one is entered. You can count on this behavior, so if you are in your save() function, you will never enter it again until the current one has finished.
Where this sometimes gets confusing (and yet remains true) is when you have asynchronous server requests (or setTimeouts or setIntervals), because then it feels like your functions are being interleaved. They're not.
In your case, while two save() calls will not overlap each other, your auto-save and user save could occur back-to-back.
If you just want a save to happen at least every x seconds, you can do a setInterval on your save function and forget about it. I don't see a need for the isSaving flag.
I think your code could be simplified a lot:
var intervalTime = 300000;
var intervalId = setInterval("save('my message')", intervalTime);
function save(showMsg)
{
if (showMsg) { //show a saving popup}
params=CollectParams();
PerformCallBack(params, endSave, endSaveError);
// You could even reset your interval now that you know we just saved.
// Of course, you'll need to know it was a successful save.
// Doing this will prevent the user clicking save only to have another
// save bump them in the face right away because an interval comes up.
clearInterval(intervalId);
intervalId = setInterval("save('my message')", intervalTime);
}
function endSave()
{
// no need for this method
alert("I'm done saving!");
}
function endSaveError()
{
alert("Ooops");
endSave();
}
All major browsers only support one javascript thread (unless you use web workers) on a page.
XHR requests can be asynchronous, though. But as long as you disable the ability to save until the current request to save returns, everything should work out just fine.
My only suggestion, is to make sure you indicate to the user somehow when an autosave occurs (disable the save button, etc).
All the major browsers currently single-thread javascript execution (just don't use web workers since a few browsers support this technique!), so this approach is safe.
For a bunch of references, see Is JavaScript Multithreaded?
Looks safe to me. Javascript is single threaded (unless you are using webworkers)
Its not quite on topic but this post by John Resig covers javascript threading and timers:
http://ejohn.org/blog/how-javascript-timers-work/
I think the way you're handling it is best for your situation. By using the flag you're guaranteeing that the asynchronous calls aren't overlapping. I've had to deal with asynchronous calls to the server as well and also used some sort of flag to prevent overlap.
As others have already pointed out JavaScript is single threaded, but asynchronous calls can be tricky if you're expecting things to say the same or not happen during the round trip to the server.
One thing, though, is that I don't think you actually need to disable the auto-save. If the auto-save tries to happen when a user is saving then the save method will simply return and nothing will happen. On the other hand you're needlessly disabling and reenabling the autosave every time autosave is activated. I'd recommend changing to setInterval and then forgetting about it.
Also, I'm a stickler for minimizing global variables. I'd probably refactor your code like this:
var saveWork = (function() {
var isSaving=false;
var timeoutId;
var timeoutInterval=300000;
function endSave() {
isSaving=false;
//hides popup if it's visible
}
function endSaveError() {
alert("Ooops");
endSave();
}
function _save(showMsg) {
//Don't save if we are already saving.
if (isSaving)
{
return;
}
isSaving=true;
if (showMsg) { //show a saving popup}
params=CollectParams();
PerformCallBack(params,endSave,endSaveError);
}
return {
save: function(showMsg) { _save(showMsg); },
enableAutoSave: function() {
timeoutId=setInterval(function(){_save(false);},timeoutInterval);
},
disableAutoSave: function() {
cancelTimeOut(timeoutId);
}
};
})();
You don't have to refactor it like that, of course, but like I said, I like to minimize globals. The important thing is that the whole thing should work without disabling and reenabling autosave every time you save.
Edit: Forgot had to create a private save function to be able to reference from enableAutoSave