Why doesn't the clearInterval() works? - javascript

I'm new to JavaScript and I'm having problems with this script.
it's part of a web game and the script is suppose to refresh the page until the player wins or loses.
for some reason it doesn't stop refreshing, I put an alert function to check if the functions works, and i get the alerts but it's still continue refreshing the page.
what am i doing wrong?
var t;
$(document).ready(function () {
intervals();
});
function intervals() {
t = self.setInterval('refreshData()', 10000);
}
function youWin() {
var f = $('#status:contains("YOU ARE THE WINNER!")');
if (f.length > 0) {
alert("YOU ARE THE WINNER!");
t = clearInterval(t);
}
}
function youlose() {
var f = $('#status:contains("You lost!")');
if (f.length > 0) {
alert("You lost!");
t = clearInterval(t);
}
}
function refreshData() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame');
youWin();
youlose();
}

You need to fix the reference to self and fix the .load() call.
.load() is asynchronous so it does not complete before you call youWin() and youLose() right after it. You need a completion function so you can check winning or losing after the .load() completes successfully.
refreshData() should be structured like this:
function refreshData() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame', function() {
youWin();
youlose();
});
}
You also should change this:
t= self.setInterval('refreshData()',10000);
to this:
t = window.setInterval(refreshData, 10000);
I don't see that self was even defined so that could have also been causing your problem and you should use the function reference directly rather than put in a string.
And, as a cleanup issue, you should change both occurences of this:
t = clearInterval(t);
to this:
clearInterval(t);
Here's a cleaned up version of the code that also eliminates global variables and unnecessary function definitions:
$(document).ready(function() {
var t = window.setInterval(function() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame', function() {
youWin();
youlose();
});
}, 10000);
function youWin() {
if ($('#status:contains("YOU ARE THE WINNER!")').length) {
alert("YOU ARE THE WINNER!");
clearInterval(t);
}
}
function youlose() {
if ($('#status:contains("You lost!")').length) {
alert("You lost!");
clearInterval(t);
}
}
});

Related

Unable to reset setTimeout timer in JavaScript

Here is my pseudocode:
if(key.pressed = 'a') {
activate = true;
}
var mytimeout = function timer_function() {
// Do stuff;
setTimeout( function() {
// do more stuff
}, 5000);
}
function some_function() {
if(activated) {
// do stuff
clearTimeout(mytimeout);
timer_function();
}
}
if(mouse.click == true) {
some_function();
}
I want the timer to be reset on each mouse click which calls some_function(). What actually happens is that the time is set on first click but never resets after that.
What am I missing?
Thanks.
mytimeout is a function, not a timeout handle. What you need to store is the result of the setTimeout call like this.
var timeoutHandle;
function timer_function() {
// Do stuff;
timeoutHandle = setTimeout( function() {
// do more stuff
}, 5000);
}
function some_function() {
if(activated) {
// do stuff
clearTimeout(timeoutHandle);
timer_function();
}
}
In function timer_function return the value of setTimeout
var mytimeout = function timer_function() {
return setTimeout( function() {
//Do some more stuff
}, 5000);
}
Thats because in you are only going to replay the Timeout only when the user presses the "a" key. I don't know why you kept it like that but thats probably the reason.!

Disable timer within setInterval function with dynamic parameters

I wanted to pass dynamic parameters into a setInterval function (see question here) and specifically #tvanfosson's comment.
But now, I also want to disable that timer if a certain condition is met. I tried to define the timer variable as a global variable but I still get the timer as a undefined on this line:
console.log('else. timer=' + timer);:
else. timer=undefined
<script language="javascript" type="text/javascript">
var timer;
var params={};
params.color='light';
$(document).ready(function () {
timer=createInterval(showSmallWidget, params.color, 500);
});
function createInterval(f, dynamicParameter, interval) {
setInterval(function () {
f(dynamicParameter);
}, interval);
}
function showSmallWidget(color) {
if ($('#widget').html() == '') {
//do stuff
}
else {
console.log('else. timer=' + timer);
if (timer) { console.log('CLEAR TIMER'); timer.clearInterval(); timer = null; }
}
}
</script>
I tried to create a JSFiddle, but I can't get it to work properly: https://jsfiddle.net/puhw3z2k/
There are a couple problems:
1) You have to return the timerID from your createInterval() function:
function createInterval(f, dynamicParameter, interval) {
return setInterval(function () {
f(dynamicParameter);
}, interval);
}
2) clearInterval() works like this clearInterval(timer), not timer.clearInterval().

Javascript: how to set intervals with a variable or run code once?

I have a problem with javascript because I want to run code in a function once until a interval is again over. So I have read about a possibilty to use an boolean to control it but without intervals and it is still calling the updatePosition() function over and over without stopping.
Simplyfied I have code in this structure:
var runPerm = false;
function start() {
setInterval(setPerm, 2000);
setInterval(function() {
new updatePosition()
}, 2000);
}
function setPerm() {
runPerm = true;
}
function updatePosition() {
if (runPerm == true) {
//some code that I want to run once.
runPerm = false;
}
}
Has someone an idea to solve the problem?
(A full code: http://pastebin.com/iSFHjct3 )
Use setTimeout.
var runPerm = false;
function start() {
setInterval(setPerm, 2000);
setTimeout(updatePosition, 2000);
}

window.settimeout in javascript loading too fast

I have this js code that has to make the height of a panel bigger on load of my page. But it seems to be loading it way too fast.
var TimerID;
function LoadDoc() {
for(i=0;i<=100;i++){
TimerID=window.setTimeout(MoveRolldownDown(i),5000);
}
}
function MoveRolldownDown(i){
document.getElementById('Rolldown').style.height=i + '%';
window.clearTimeout(TimerID);
}
This loads in the page nearly instantly, so how can i make this load slower. At the top of my HTML page i have this code
document.onreadystatechange = function () {
if(document.readyState === "complete"){
LoadDoc();
}
}
1st thing -- your functions are executing immediately so you need to put them inside of another function.
One more thing -- all of your timeouts end at basically the same time!
Try something like this:
function LoadDoc() {
for (i = 0; i <= 100; i++) {
var down = i;
setTimeout((function (down) {
return function(){ //return function for timeout
MoveRolldownDown(down);
};
})(i), 10 * i);
}
}
function MoveRolldownDown(i) {
document.getElementById('Rolldown').style.height = i + '%';
}
Demo: http://jsfiddle.net/maniator/RTaZh/
Yes, it because you are calling the function within the parameters,
You probably want something like
window.setTimeout(MoveRolldownDown,5000, [i]);
https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout

setTimeout keeps firing, how to make it fire only once?

I am making a simple chat, it works in different browsers but setTimeout keeps firing, and I want it to fire only once as it is pointless to keep firing and I believe also it would cause more stress on the server.
This is the function which is called from somewhere else:
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
setTimeout("chat_load();", 1000);
});
}
I tried something like the following but it just keeps on firing. Also, the function is supposed to fire only when a certain button is clicked, which happens only once every so often.
var c = 0;
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
var t = setTimeout("chat_load();", 1000);
c++;
if (c == 3) {
clearTimeout(t);
}
});
}
I think you want something like this:
var c = 0, t;
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
clearTimeout(t);
t = setTimeout(chat_load, 1000);
if (++c === 3) {
clearTimeout(t);
c=0;
}
});
}
You can't change variables in a asynchronous function
c++; wont work
maybe you should do this
function addCount() {
c++;
}
and change c++ to addCount();
so this
var c = 0;
function addCount() {
c++;
}
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
var t = setTimeout("chat_load();", 1000);
addCount();
if (c == 3) {
clearTimeout(t);
}
});
}

Categories

Resources