clearInterval not working in jquery - javascript

i am using jquery function setinterval and than clearinterval to clear it.. but i the clearinterval is not working .. here is my code.
$('#autoslide').click(function(){
if($('#autoslide').is(':checked')){
var interval = setInterval(function() {
$('.magazine').turn('next');
}, 2000);
}else
{
//stopinterval(interval)
clearInterval(interval);
//window.clearInterval(interval);
// interval = null
}
});
none of these tries are working

Make your timer variable outside the function.
var interval;
$('#autoslide').click(function(){
if($('#autoslide').is(':checked')){
interval = setInterval(function() {
$('.magazine').turn('next');
}, 2000);
}else
{
//stopinterval(interval)
clearInterval(interval);
//window.clearInterval(interval);
// interval = null
}
});

You need to use a global variable. If you use a local variable, each click handler invocation has its own copy of the variable.
var interval;
$('#autoslide').click(function(){
if($('#autoslide').is(':checked')){
interval = setInterval(function() {
$('.magazine').turn('next');
}, 2000);
}else
{
//stopinterval(interval)
clearInterval(interval);
//window.clearInterval(interval);
// interval = null
}
});

Related

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

How can I stop custom jQuery function which is running?

I have a custom jQuery function. When it runs every 5 seconds.
(function($) {
$.fn.mycustomfunction = function() {
interval = setInterval(function() {
console.log("I am running every 5 seconds");
}, 5000);
}
return this;
};
})(jQuery);
$("#container").mycustomfunction();
I have a
clearInterval(interval);
to stop, but I also want to stop the function completely. How can I do that ?
Functions you add to this object will be attached to your object and Simple and naive solution will follow:
(function($) {
$.fn.mycustomfunction = function() {
interval = setInterval(function() {
console.log("I am running every 5 seconds");
}, 1000);
this.stop= function(){
clearInterval(interval);
}
// another function
this.alert = function(msg){
alert(msg)
}
return this;
};
})(jQuery);
to stop use
var feature = $("#container").mycustomfunction();
feature.stop();

Javascript ClearTimeout doesnt work

I'm looking for a solution for my code. My clearTimeout function doesn't work in the stop(); and start(); functions, does anybody know how to fix this?
The stop, start and reset button have all a setTimeout function. What I would like to do is that if is clicked at one of the buttons, the other two buttons have cleartimeout. But for somehow it doesn't working right now.
var isTimerStarted;
var timeOutElse;
var timeOut;
var opnieuw;
function start() {
clocktimer = setInterval("update()", 1);
x.start();
isTimerStarted = true;
timeOutElse = setTimeout(function(){
document.getElementById("scherm3").style.display = "block";
document.getElementById("scherm2.2").style.visibility = "hidden";
}, 8000)
}
function stop() {
x.stop();
clearInterval(clocktimer);
isTimerStarted = false;
timeOut = setTimeout(function(){
document.getElementById("scherm4").style.visibility = "visible";
document.getElementById("scherm2.2").style.visibility = "hidden";
}, 4000)
}
function reset() {
stop();
x.reset();
update();
opnieuw = setTimeout(function(){
document.getElementById("scherm3").style.display = "block";
document.getElementById("scherm2.2").style.visibility = "hidden";
}, 10000);
clearTimeout(timeOut);
clearTimeout(timeOutElse);
document.getElementById("buttontimer").value = "Start";
}
setTimeout(start, 5000);
function toggleTimer(event) {
if (isTimerStarted) {
stop();
event.target.value = 'Start';
clearTimeout(opnieuw);
clearTimeout(timeOutElse);
} else {
start();
event.target.value = 'Stop';
clearTimeout(opnieuw);
clearTimeout(timeOut);
}
}
There's nothing wrong with your code, from what I can tell.
But I think you might have forgot to remove a line from it.
setTimeout(start, 5000); is creating timeouts after 5 seconds whatever/whenever you click a thing.
It is what could create timing issues.
Here's a scenario that could happen:
you click
toggleTimer() -> start() -> create timeout and interval
5s later your setTimeout(start, 5000) executes and reassign your timeout and interval variables
you re-click
latest timeout and interval gets cleared, but not the first ones
Just to be safe, you could clear, at the beginning of each of your functions, the timeouts and intervals you're creating in the said function.
This way, you will always clear timeouts and intervals that gets created.

use onmousemove to reset setTimeout() to start over again(・・?

when mouse moves, the timer function cancelled =="
but i actually want it to count from the beginning instead.
function w()
{
if (parent.C.location == "http://119.247.250.128/wasyoku/home/prime.html")
{ parent.C.location = "weather.html";
wTout = setTimeout(function(){ parent.C.location = "prime.html"; }, wT);
}
else { parent.C.location = "prime.html"; clearTimeout(wTout); }
}
document.onmousemove.clearTimeout(wTout);
do i really need to setTimeout again(・・?
wTout = setTimeout(function(){ parent.C.location = "prime.html"; }, wT);
Yes, if you clear the timeout you have to set it again.
Another thing you can do is set a variable as the last time you moved the mouse and on the ontimeout you can set another settimeout if you moved the mouse in XX seconds
var sto = null;
function myTimeout() {
window.clearTimeout(sto);
sto = setTimeout(function() {
console.log("setTimeout's working");
}, 2000);
}
someElement.addEventListener('mousemove', function() {
myTimeout();
});
jsfiddle DEMO

Resetting a setTimeout

I have the following:
window.setTimeout(function() {
window.location.href = 'file.php';
}, 115000);
How can I, via a .click function, reset the counter midway through the countdown?
You can store a reference to that timeout, and then call clearTimeout on that reference.
// in the example above, assign the result
var timeoutHandle = window.setTimeout(...);
// in your click function, call clearTimeout
window.clearTimeout(timeoutHandle);
// then call setTimeout again to reset the timer
timeoutHandle = window.setTimeout(...);
clearTimeout() and feed the reference of the setTimeout, which will be a number. Then re-invoke it:
var initial;
function invocation() {
alert('invoked')
initial = window.setTimeout(
function() {
document.body.style.backgroundColor = 'black'
}, 5000);
}
invocation();
document.body.onclick = function() {
alert('stopped')
clearTimeout( initial )
// re-invoke invocation()
}
In this example, if you don't click on the body element in 5 seconds the background color will be black.
Reference:
https://developer.mozilla.org/en/DOM/window.clearTimeout
https://developer.mozilla.org/En/Window.setTimeout
Note: setTimeout and clearTimeout are not ECMAScript native methods, but Javascript methods of the global window namespace.
You will have to remember the timeout "Timer", cancel it, then restart it:
g_timer = null;
$(document).ready(function() {
startTimer();
});
function startTimer() {
g_timer = window.setTimeout(function() {
window.location.href = 'file.php';
}, 115000);
}
function onClick() {
clearTimeout(g_timer);
startTimer();
}
var myTimer = setTimeout(..., 115000);
something.click(function () {
clearTimeout(myTimer);
myTimer = setTimeout(..., 115000);
});
Something along those lines!
For NodeJS it's super simple:
const timeout = setTimeout(...);
timeout.refresh();
From the docs:
timeout.refresh()
Sets the timer's start time to the current time, and reschedules the timer to call its callback at the previously specified duration adjusted to the current time. This is useful for refreshing a timer without allocating a new JavaScript object.
But it won't work in JavaScript because in browser setTimeout() returns a number, not an object.
This timer will fire a "Hello" alertbox after 30 seconds. However, everytime you click the reset timer button it clears the timerHandle then re-sets it again. Once it's fired, the game ends.
<script type="text/javascript">
var timerHandle = setTimeout("alert('Hello')",3000);
function resetTimer() {
window.clearTimeout(timerHandle);
timerHandle = setTimeout("alert('Hello')",3000);
}
</script>
<body>
<button onclick="resetTimer()">Reset Timer</button>
</body>
var redirectionDelay;
function startRedirectionDelay(){
redirectionDelay = setTimeout(redirect, 115000);
}
function resetRedirectionDelay(){
clearTimeout(redirectionDelay);
}
function redirect(){
location.href = 'file.php';
}
// in your click >> fire those
resetRedirectionDelay();
startRedirectionDelay();
here is an elaborated example for what's really going on http://jsfiddle.net/ppjrnd2L/
i know this is an old thread but i came up with this today
var timer = []; //creates a empty array called timer to store timer instances
var afterTimer = function(timerName, interval, callback){
window.clearTimeout(timer[timerName]); //clear the named timer if exists
timer[timerName] = window.setTimeout(function(){ //creates a new named timer
callback(); //executes your callback code after timer finished
},interval); //sets the timer timer
}
and you invoke using
afterTimer('<timername>string', <interval in milliseconds>int, function(){
your code here
});
$(function() {
(function(){
var pthis = this;
this.mseg = 115000;
this.href = 'file.php'
this.setTimer = function() {
return (window.setTimeout( function() {window.location.href = this.href;}, this.mseg));
};
this.timer = pthis.setTimer();
this.clear = function(ref) { clearTimeout(ref.timer); ref.setTimer(); };
$(window.document).click( function(){pthis.clear.apply(pthis, [pthis])} );
})();
});
To reset the timer, you would need to set and clear out the timer variable
$time_out_handle = 0;
window.clearTimeout($time_out_handle);
$time_out_handle = window.setTimeout( function(){---}, 60000 );

Categories

Resources