Disable timer within setInterval function with dynamic parameters - javascript

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().

Related

clearInterval() not working and returns no errors

I would like to run a function, when a checkbox is checked and stop that function, when the checkbox is not checked.
This is how I tried it:
$('#auto').on('click', function() {
if ($(this).is(':checked')) {
// Interval
var autoInterval = window.setInterval(function() {
navi('next');
}, 1500);
}
else {
clearInterval(autoInterval);
}
});
The problem is clearInterval() does not work and I get no errors.
https://jsfiddle.net/n339tzff/9/
It will work if my code looks like this:
// Interval
var autoInterval = window.setInterval(function() {
navi('next');
}, 1500);
// Auto Play
$('#auto').on('click', function() {
if ($(this).is(':checked')) {
autoInterval;
}
else {
clearInterval(autoInterval);
}
});
But then I have another problem... I only want to run the function navi('next') when I click on the checkbox and not at the beginning.
When you click, it calls the setInterval and stores the result of the call in the autoInterval and after ending the function removes it. So you store and lost the value of your variable every time in the same call.
Declare the autoInterval variable outside of the event handler, to make it independent from the event handler's scope. Also you can wrap your function with a IIFE to not mutate this variable outside
(function() {
var autoInterval;
$('#auto').on('click', function() {
if ($(this).is(':checked')) {
autoInterval = window.setInterval(function() {
navi('next');
}, 1500);
} else {
clearInterval(autoInterval);
}
});
})();
You should define autoInterval outside of the event handler function, as after the event has run this variable would be 'discarded'/un-accessable.
var autoInterval = null;
$('#auto').on('click', function () {
if ($(this).is(':checked')) {
autoInterval = window.setInterval(function () {
navi('next');
}, 1500);
}
else if(autoInterval !== null) {
clearInterval(autoInterval);
autoInterval = null;
}
});

How to make clearTimeout() happen within setTimeout()?

I have a setTimeout function already running to make a watch work, but I want to clearTimeout on this already running function when I clock on a button, but only after a few seconds. So ideally, I want a clearTimeout() inside another setTimeout() function, but I can't seem to get it working.
I have this code at the moment:
alarm.click(function() {
water.animate(anim);
setTimeout(function () { clearTimeout(time); }, 3000);
});
var time = setTimeout(function(){ startTime() },1000);
But it does it clears it straight away rather than after 3 seconds. What can I do to make it clear after 3 seconds?
edited my code, still not working :(.
You can try:
var time = setTimeout(function(){startTime(time)},1000);
And in startTime you clear time
function startTime(time) {
cleartTimeout(time);
...
}
You are calling it straight away, but you need a callback.
setTimeout(function () { clearTimeout(time); }, 3000);
function startTime() {
document.getElementById('out').innerHTML += 'starttime<br>';
}
function set() {
document.getElementById('out').innerHTML += 'set<br>';
setTimeout(function () {
document.getElementById('out').innerHTML += 'clear3000<br>';
clearTimeout(time);
}, 3000);
}
var time = setTimeout(function () {
document.getElementById('out').innerHTML += 'clear1000<br>';
startTime();
}, 1000);
set();
<div id="out"></div>

why setTimeout() only run my code once,at first time? [duplicate]

This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 8 years ago.
i use this javascript code to open two pictures and toggle a vertical menu by clicking on another picture. an know i want to run code without clicking on image, with a timer. so i wrote this code but it run only once at first time.
what's wrong with my code?
<script type="text/javascript">
$(document).ready(function () {
$("#lista2").slideToggle(1);
$curtainopen = false;
$(".rope").click(function () {
$(this).blur();
if ($curtainopen == false) {
var selected = $(this).val();
var image = $(".rope");
image.fadeOut('fast', function () {
$("#largeImg").attr('src', 'images/power-on.png');
image.fadeIn('fast');
});
$(".leftcurtain").stop().animate({ left: '-120px' }, 2000);
$(".rightcurtain").stop().animate({ left: '120px' }, 2000);
$("#R").attr('src', 'images/Right.gif');
$("#L").attr('src', 'images/Left.gif');
$curtainopen = true;
$("#lista2").slideToggle(2000);
$(this).attr('id', '1');
} else {
var selected = $(this).val();
var image = $(".rope");
image.fadeOut('fast', function () {
$("#largeImg").attr('src', 'images/power-off.png');
image.fadeIn('fast');
});
$(".leftcurtain").stop().animate({ left: '0px' }, 2000);
$(".rightcurtain").stop().animate({ left: '0px' }, 2000);
$curtainopen = false;
$("#lista2").hide();
$(this).attr('id', '0');
}
return false;
});
});
function startTimer() {
setTimeout($(".rope").click(), 4000);
}
</script>
use this to execute your code after a specific time interval
setInterval(function() {
$(".rope").click(); // this will execute after every 4 sec.
}, 4000);
use this to execute your code after a specific time delay
setTimeout(function() {
$(".rope").click(); // this will execute after 4 sec delay only once.
}, 4000);
use above according to your requirement
setTimeout need a function, When you are passing $(".rope").click() it is called immediately.
Use it like
function startTimer() {
setTimeout(function () {
$(".rope").click();
}, 4000);
}
setTimeout(function() {
$(".rope").click();
}, 4000);
because setTimeout needs a function, but $(".rope").click() calls itself immediatly (instead of assigning a function to be called). So you don't want to call a function but to pass it to setTimeout.
A timer implies repeating the function after each timeout. setTimeOut only delays a function once (after a given time, in milliseconds).
function startTimer() {
//do your stuff
$(".rope").click();
//repeats itself after 4 seconds
setTimeout(startTimer, 4000);
}
And do not forget to start it on document ready :
$(document).ready(function () {
startTimer();
...
}
I you don't want your function to be called immediately on page load, you can add an initial delay :
$(document).ready(function () {
setTimeout(startTimer, 5000); //the timer will start only 5 seconds after page load
...
}

Stop a Jquery/Javascript timer

I know this can't be that difficult, but I swear I can't find a straight forward answer to this. I have the following javascript/jquery function that starts a timer:
function startTimer() { (function ($) {
//timer for the box
window.timer = window.setInterval(function() {
$(".region-brand-window").timer();
}, 10000);
jQuery.fn.timer = function() {
changeBrandOnTimer();
}
})(jQuery); }
How do I stop this thing? And I don't mean pause. I mean turn it off from another function.
clearInterval(window.timer);
Should do it.
To cancel an interval, you would use:
clearInterval(window.timer);
FYI, if it was a timeout you would use clearTimeout() in the same way.
use window.clearInterval(intervalID)
window.clearInterval(window.timer)
call stopTimer whenever you want to stop timer.
function startTimer() { (function ($) {
//timer for the box
window.timer = window.setInterval(function() {
$(".region-brand-window").timer();
}, 10000);
jQuery.fn.timer = function() {
changeBrandOnTimer();
}
})(jQuery); }
function stopTimer(){
clearInterval(timer );
}

Why doesn't the clearInterval() works?

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);
}
}
});

Categories

Resources