javascript: setInterval execute with out stoping - javascript

I am creating a chrome extension and I need to use an interval.
The time the interval will go off every time is chosen by the user itself.
The function executes on every open tab and sends data to it.
My problem is that the "timer" dosn't work like it should, it just execute all at once like a normal while loop.
Here is the code:
chrome.tabs.query({}, function (tabs) {
//the times the code need to run is by the amount of tabs that is open
setInterval(function () {
if (i < tabs.length) {
chrome.tabs.sendRequest(tabs[i].id, { input: "uCanSend",
userName: myName,
password: myPass,
subject: mySubject, msg: myMsg,
linkName1: myLinkName1,
linkURL1: myLinkURL1,
linkName2: myLinkName2,
linkURL2: myLinkURL2
}, function (response) { });
}
i++;
}, timeInMintus //the time that the code need to run every time);
});
I have no idea what am I doing wrong.
Any idea how to fix it that it will run correctly?
(sorry for my English)

The second argument needs to be in milliseconds (thousandths of a second). Based on the variable name, it looks like you're passing minutes. For example, if you want the callback to run every minute:
setInterval(function () { /* snip */ }, 1000*60);

Chrome queues up setTimeout/setInterval calls on inactive tabs and changes the minimal timeout length.

Related

Continuously calling function in background

The problem
I am saving pictures in my IndexedDB on the browser. I want to call a function in javascript every 10 seconds to sync the URL's in the IndexedDB to my real database.
It should be down in the backgroud. This means: There should be a function which will be called every 10 seconds to automaticall "sync" the entries in the database.
What i have done
I have already a "sync"-Button/functionality which works fine. This function should be called automatically. But this function in the background should not interrupt or distrubt my main functions in the foreground. For example adding new entries in the indexedDB.
During my research i found the folliwing function:
setInterval(function(){ alert("Hello"); }, 3000);
But it just works alone and not parallel with my "main"-functions.
The ideal solution
The ideal solution should be a function (i have the function already) which will be triggered ever 10 seconds (it don't have to be really 10 seconds, this is just a sample number) but should not disurpt other functions by executing.
If you just want to call your function again and again, try this code using setTimeInterval:
/* The data param is in case you want to pass some param */
var mySynFunc = (data) => {
console.log(`Sync my data: ${data}`);
}
/* This id must be used to stop your function interval */
var id = setInterval(mySynFunc, 3000, 'my-url');
/* If you want to stop your setIntervalFunction use this */
clearInterval(id)

Wrong use of Javascript setInterval()

I have a function called using setInterval of JavaScript, which in some scenarios is called multiple times without the interval gap defined (I suspect this is because the intervals are not cleared properly and I'm creating multiple intervals, but I'm not sure).
I can not reproduce the problem locally.
The code uses Twirl but it's basically JS:
function refreshCheckInRequests() {
if (interval) { // If there is an interval running stop it.
clearInterval(interval);
}
jsRoutes.controllers.ExtranetSecuredController.findPendingCheckInRequests("#gymId").ajax({ // Ajax call using Play Framework
success: function (data) {
$("#checkin-request-container").html(data);
addRowListeners()
},
error: function (data) {
if (data.status == 401) {
errorSwitchGym("#Messages("extranet.switch.gym")");
//location.reload();
}
else {
unexpectedError(data)
}
},
complete: function() {
interval = initInterval(); // At the end of the call init the interval again
}
});
}
function initInterval() {
return setInterval(function () { refreshCheckInRequests(); },
20000);
}
var interval;
refreshCheckInRequests();
$("#checkin-request-refresh").click(function (event) {
refreshCheckInRequests();
event.preventDefault();
});
I could use setTimeout instead because at the end, I always call refreshCheckInRequests once, I stop the interval, and at the end I create a new one.
If I use timeout I have to call again my function at the end of the execution of the callback of timeout (like I'm doing right now). If something goes wrong, my callback will never be called again.
Anyway, I would like to know what's going on here. Am I missing something? Am I doing something wrong? Any suggestions?
You're clearing the current interval every time refreshCheckInRequests is called, but there is a delay between when refreshCheckInRequests is called and the new interval is assigned. Because refreshCheckInRequests also runs when an element is clicked, the following scenario could result in an unterminated interval:
User clicks, current interval is cleared, asynchronous findPendingCheckInRequests runs
User clicks again, no interval currently exists (nothing to clear), another asynchronous findPendingCheckInRequests runs
Response from first findPendingCheckInRequests comes back. complete handler runs, interval is assigned to the new interval
Response from second findPendingCheckInRequests comes back. complete handler runs, interval is assigned to the new interval over the old interval
The first created interval remains running, but there no longer exists a reference to it, so that first interval continues repeating forever.
So, try clearing the interval at the moment you reassign interval, ensuring that every new interval will always clear the old one, if an old one is running:
complete: function() {
clearInterval(interval);
interval = initInterval();
}

window.setInterval in Javascript do not run a function more than once

I want to update a partial view every 5000 ms (for example).
I used bellow code to do it:
window.setInterval(function () {
$.get("/Features/ShowDateTime").then(function (r) {
$('#divDateTime').html(r);
});
}, 5000)
This function run every 5000 ms truly (examined by using debugger command in the inner function) but ShowDateTime action run once (examined by using break-point in the action in its controller).
So, what is the problem?
Assuming the code itself is working, it is likely you are getting cached data back on subsequent calls. You need to cache-bust your calls. An easy way is to simply append the current timestamp to the end of the URL:
window.setInterval(function () {
$.get("/Features/ShowDateTime?" + Date.now()).then(function (r) {
$('#divDateTime').html(r);
});
}, 5000)
This will cause your browser to think it is a different URL each time so it won't cache and return the same result.

How to submit a request for some given condition using jscript and jquery?

I have tried this code:
while (true) {
$(document).ready(function() {
setInterval(function () {
if ($("h2").text() == "Qu’est-ce qu’une année-lumière ?") {
$("#choice2").delay(200).queue(function () {
$(this).click().dequeue()
})
}
}, 10000)
}
. My aim is actually to send an answer as the page DOM is already ready if the element in the tag is verified, then i want to repeat this for as i am on that page. I tried many codes but my browser doesn't like them: it freezes... that is why i try to use an interval, but i am unable to control it yet. please i need your help...
The browser freezes because you have an infinite loop. It will just keep binding more and more ready events until the code is stopped for taking too long to run, or when the browser crashes because you have bound a zillion event handlers.
Adding the interval was the right move to make the code run more than once, but the while loop still kept it from working.
Remove the while loop, and your code will run. You don't need to dequeue a function that you queued, it will be dequeued when it runs.
$(document).ready(function() {
setInterval(function () {
if ($("h2").text() == "Qu’est-ce qu’une année-lumière ?") {
$("#choice2").delay(200).queue(function () {
$(this).click();
});
}
}, 10000);
}
The interval runs the code every 10 seconds, so there doesn't seem to be any reason to wait for 200 ms before invoking the click, though.

setInterval stops without any reason when browser tab is background

I am working on an application that sends current timestamp to database every 2 minutes with AJAX using setInterval.
But somehow setInterval stops after some minutes (i didnt calculate the exact time), but i believe it happens when i dont open that browser's tab for 20-30 minutes.
function tmstmp() {
$.post("send_functions.php?act=time");
}
$(function() {
setInterval(tmstmp, 60000);
});
Is that normal that setInterval stops if that tab is not on foreground ?
If yes, how can i prevent setInterval to stop ? or check if it stopped ?
Thanks
You should try to make an function call on page startup:
test();
and then loop that function:
function test() {
setTimeout(function() {
// your code
test();
}, 2000);
}
That's not supposed to happen.
Browsers may indeed reduce the timer resolution to something around 1/s, but not clear the setInterval.
Could there be some bug in your code that causes a clearInterval?
No code + no debug information = hard to tell what went wrong.
Just to be sure add the following line to the code (method) that gets executed with setInterval and watch after 20-30 minutes if you still get output in the console.
console.log('Yep! I am alive!');
EDIT: Could be anything but try changing the tmstmp method to include a callback function after the POST request gets executed. That way you'll at least know that it works.
function tmstmp() {
$.post("send_functions.php?act=time", function(data){
console.log('Yep! I am alive!');
});
}

Categories