So I have this function to check when a opponent is connected. Everything works, except the clearInterval thing... I tried adding window.setInterval and window.clearInterval . I tried adding self. too...
$(document).ready(function() {
var waitForOpponent = setInterval(checkUserStatus, 2000);
function checkUserStatus() {
$('#user').load('checkuser.php?randval='+ Math.random());
$("#user").ajaxStop(function(){
if(document.getElementById("user").innerHTML!=""){
clearInterval(waitForOpponent);
opponentConnected();
}
});
}
});
I also tried to go like this:
var waitForOpponent;
function check() { waitForOpponent = setInterval(checkUserStatus, 2000); }
check();
Please help me out guys.. I tried everything...
Get rid of ajaxStop and use the success callback of the .load.
$('#user').load('checkuser.php?randval='+ Math.random(),function(){
if(document.getElementById("user").innerHTML!=""){
clearInterval(waitForOpponent);
opponentConnected();
}
});
if the requests are taking longer than 2 seconds, ajaxstop will never be called.
A better alternative in my opinion is to not use setInterval:
function checkUserStatus() {
$('#user').load('checkuser.php?randval='+ Math.random(),function(){
if(document.getElementById("user").innerHTML!=""){
opponentConnected();
return; // exit
}
setTimeout(checkUserStatus,2000); // continue after 2 seconds
});
}
checkUserStatus(); // start it up
this prevents the ajax requests from piling up on slow connections or on timeouts.
Related
I'm trying to make a chrome extension and in my content script which runs only on www.youtube.com it's supposed to check, document.getElementById("movie_player"), if a particular div element has loaded or not. If not setInterval and wait a second. If it has loaded then run alert("Hello") and clearInterval which will end the script.
However, it's not working. Even after I find the element, and it says "Hello" it continues to say hello which means setInterval is still calling my function after 1000 milliseconds even though it should have been cleared.
Here's my content.js file:
var timeOut;
function CheckDOMChange()
{
moviePlayer = document.getElementById("movie_player");
if(moviePlayer !== null)
{
WhenVideoLoads();
}
timeOut = setInterval("CheckDOMChange();", 1000);
}
function WhenVideoLoads()
{
alert("Hello");
clearInterval(timeOut);
}
CheckDOMChange();
As you can see, I made timeOut a global variable so it shouldn't be a scope problem. So I really don't know what the problem is because the condition is being met and clearInterval is being called.
Any help would be much appreciated.
The issue is that you have setInterval inside the function. Basically, for every call you are setting interval which creates multiple setIntervals. Remove the setInterval from within the function
var timeOut;
function CheckDOMChange() {
moviePlayer = document.getElementById("movie_player");
if (moviePlayer !== null) {
WhenVideoLoads();
}
}
function WhenVideoLoads() {
alert("Hello");
clearInterval(timeOut);
}
timeOut = setInterval("CheckDOMChange();", 1000);
By calling CheckDOMChange recursively, you are actually exponentially creating timers, and you are only clearing the last timer when calling WhenVideoLoads.
You may try to run this snippet and inspect the console to see what is happening, and see that clicking the button will clear the last timer but not all those that have been created before.
var timeOut;
var counter = 0;
function CheckDOMChange()
{
console.log("counter :", counter);
if (counter > 16) {
console.log("Stop creating new timers!");
return;
}
timeOut = setInterval("CheckDOMChange();", 5000);
console.log("timeOut :", timeOut);
counter ++;
}
function WhenVideoLoads()
{
console.log("Clearing ", timeOut);
clearInterval(timeOut);
}
CheckDOMChange();
<button onclick="WhenVideoLoads()" id="clear">Clear timer</button>
You should avoid calling CheckDOMChange recursively, and proceed as #cdoshi suggested.
Hope this helps!
I need a javascript while look that looks for the condition ":visible" on a DOM object and only runs the code when the DOM object is actually visible.
This is my code so far.
if (("#rightPanel").is(":visible") == true){
// It's visible, run fetch on interval!
setInterval(function() {
updateChatField()
}, 500);
} else {
// Do Nothing!
};
What do I need to adjust to get my desired effect? Right now I'm getting ("#rightPanel").is is not a function.
You forgot the $ sign:
if ($("#rightPanel").is(":visible") == true){
// It's visible, run fetch on interval!
setInterval(function() {
updateChatField()
}, 500);
} else {
// Do Nothing!
};
Actually, if I understood correctly, you need the interval to be constantly running so it detects when the element changes to visible. I'd suggest something like:
var $rightPanel; // cache the element
function checker() {
if ($rightPanel.is(":visible"))
updateChatField();
}
function init() {
$rightPanel = $("rightPanel"); // cache
window.setInterval(checker, 500);
}
Then to start it, just call init() after the page has loaded.
I'm writing a script, and there are two boolean statements that are very similar but giving different results, and I don't see why they conflict with one another.
My function looks like this:
SCRIPT:
(function() {
window.onload = function() {
let stopped = true;
let button = document.getElementById("start-stop");
if (stopped) {
setInterval(function() {
console.log("The timer is working.");
}, 1000);
}
button.addEventListener('click', function(){
if (stopped) {
stopped = false;
console.log(stopped);
} else {
stopped = true;
console.log(stopped);
}
});
}
}
}).call(this);
The basic idea is that when I push the button the setInterval function stops, however it keeps on going even when the if/else function switches stopped to false.
For example, my console.log looks like this:
I.e. stopped = false, but setInterval doesn't terminate.
Why is this not evaluating correctly?
The problem with your code is that you are trying to work on a piece of code that has already started to operate. In simpler words, the setInterval method will be called every 1000ms, no matter what the value of stopped variable is. If you wish to really stop the log, you can do any of these:
clearInterval()
to completely remove the interval or
setInterval(function() {
if (stopped) {
console.log("The timer is working.");
}
}, 1000);
to check if the value of stopped variable has changed or not (after the click) and act accordingly. Choose either of these for your purpose..
you are calling setinterval even before button is clicked .As the event is already triggered you cannot stop just by setting the variable to false ,you need to clear the interval using clearinterval
check the following snippet
var intervalId;
window.onload = function() {
let stopped = true;
let button = document.getElementById("start-stop");
var Interval_id;
button.addEventListener('click', function() {
if (stopped) {
Interval_id = callTimeout();
stopped = false;
} else {
clearInterval(Interval_id);
stopped = true;
}
});
}
function callTimeout() {
intervalId = setInterval(function() {
console.log("The timer is working.");
}, 1000);
return intervalId;
}
<input type="button" id="start-stop" value="click it">
Hope it helps
Put the if(stopped) statement inside the setInterval function because if you used this function once it will keep going..
Another way to stop setInterval function is by using clearInterval, like this
var intervalId = setInterval(function() { /* code here */}, 1000)
// And whenever you want to stop it
clearInterval(intervalId);
When you click the button stopped variable becomes false but the setInterval will not stop because the setInterval code is already executed.. it will not execute again on button click. And if you reload the page what will happen is that stopped variable will be again set to true as you have written at first line and setInterval will execute again ..
Now What you can do is store setInterval in a variable like this
var timer = setInterval(function,1000);
and then when you click the button use this method to clear interval
clearInterval(timer);
this should do the trick .. Hope it helps ..
I utilized this resource to structure my code: http://www.w3schools.com/jsref/met_win_clearinterval.asp
var intervalID = setInterval(function(){ ogpeWrapper() }, 10);
function ogpeWrapper() {
$("#breadcrumbWrapper, #leftColWrapper, #rightColWrapper").wrapAll('<div id="colWrapperContainer"></div>');
}(jQuery);
function myStopFunction() {
if (document.getElementById('colWrapperContainer')) {
clearInterval(intervalID);
setIntervalID = undefined;
}
}
My ogpeWrapper function is running, but the clearInterval function is not.
Basically, once $("#breadcrumbWrapper, #leftColWrapper, #rightColWrapper").wrapAll(''); runs, I want the interval to stop running it.
Edit - 12:24pm CST:
This is the base code I utilize to wrap the listed elements -
(function($) {
$("#breadcrumbAds, #breadcrumbWrapper, #containerTopParsys, #leftColWrapper, #rightColWrapper").wrapAll('<div id="colWrapperContainer"></div>');
})(jQuery);
This code works, but it doesn't process the change until after the DOM has completely loaded. I need the function to work as soon as those elementals are all available. So I need to use a setInterval to process the function, then clear the interval once the function is processed.
If anyone knows of another way to do this, besides a setIterval, please let me know.
You need to create a definite if else condition within the variable so you know exactly when it will start and when it will stop. Also, because the minimum millisecond interval timing is not consistent across browsers, although you want it to detect really fast, I would recommend a "safer" number and use 100 as the minimum instead. The .length method is a handy little way for you to check if an element is on a page; You can use it as a pseudo dynamic true/false conditional. Lastly, in your .wrapAll() tag, I swapped your single and double quotes, as it is best practice to do such.
var colWrapper = setInterval(function(){
if ($('div#colWrapperContainer').length > 0) {
var doNothing = "";
clearInterval(colWrapper);
} else {
$("#breadcrumbWrapper, #leftColWrapper, #rightColWrapper").wrapAll("<div id='colWrapperContainer'></div>");
}
}, 100);
Here is a working example for your reference Wrap Example
Update:
Example for putting the script inside the <body> tag (no window.load/document.ready) so that it runs independently as soon as it is loaded.
<script type="text/javascript">//<![CDATA[
//http://stackoverflow.com/questions/33483000/clearinterval-function-not-clearing-setinterval-function/33483267#33483267
//Auto Wrap Solution
//Alexander Dixon [11-02-2015]
var wrapThese = $("#breadcrumbWrapper, #leftColWrapper, #rightColWrapper");
var colWrapper = setInterval(function () {
if ($('div#colWrapperContainer').length > 0) {
var doNothing = "";
clearInterval(colWrapper);
} else {
wrapThese.wrapAll('<div id="colWrapperContainer"></div>').addClass('success');
}
}, 100);
//]]>
</script>
I have some code sort of like this:
function myFunction(){
$('#somediv').html("Making request...");
$.get('/script.php',
function(data){
if(data.error == 0){
$('#somediv').html("yay!");
} else {
$('#somediv').html("oops!");
window.setTimeout(myFunction(), 2000);
}
},
'json');
}
The "oops!" never displays, I believe possibly because the $.get() request is being called asynchronously. The only way I can make it display is if I wrap it in a window.setTimeout() or run an alert() before it.
Follow your code line by line, and you'll understand what's happening.
function myFunction(){
$('#somediv').html("Making request...");
$.get('/script.php',
function(data){
if(data.error == 0){
$('#somediv').html("yay!");
} else {
$('#somediv').html("oops!");
myFunction();
}
},
'json');
}
$('#somediv').html("Making request...");
$.get()
// waiting for ajax request...
$('#somediv').html("oops!");
$('#somediv').html("Making request...");
steps 4 and 5 are happening within .01 ms most likely, which is why you never see "oops!".
You can use a settimeout around myfunction to make oops visible, but it would likely be better to instead just not display anything so that it just continues to say "Making Request...".
Use:
window.setTimeout(myFunction, 2000);
instead of
window.setTimeout(myFunction(), 2000)
window.setTimeout(myFunction(), 2000); calls myFunction() and it's same with: window.setTimeout(undefined, 2000) because myFunction() returns undefined.
But when myFunction is called you rewrite the html using $('#somediv').html("Making request...");.