Destroy previous setInterval - javascript

I want a function to set an Ajax and a reload timer. The code below doesn't destroy the previous function call timer, so each time I invoke it I get another timer. How can I destroy the previous timer?
function initNowPlayingMeta(station) {
$('#cancion').children().remove();
$('#cancion').load('sonando.php?emisora=' + station);
var prevNowPlaying = setInterval(function () {
$('#cancion').load('sonando.php?emisora=' + station);
}, 5000);
}

You need to store your timer reference somewhere outside of local scope (this essentially means declaring it with var outside of the function). Then, clear it with clearInterval:
var prevNowPlaying = null;
function initNowPlayingMeta(station) {
if(prevNowPlaying) {
clearInterval(prevNowPlaying);
}
$('#cancion').children().remove();
$('#cancion').load('sonando.php?emisora=' + station);
prevNowPlaying = setInterval(function () {
$('#cancion').load('sonando.php?emisora=' + station);
}, 5000);
}

clearInterval
clearInterval(prevNowPlaying);
you will also want to make the prevNowPlaying from previous calls in scope whereever you try to cancel

You need to explicitly clear the timer.
var prevNowPlaying;
function initNowPlayingMeta(station) {
$('#cancion').children().remove();
$('#cancion').load('sonando.php?emisora=' + station);
if (prevNowPlaying === undefined) clearInterval(prevNowPlaying);
prevNowPlaying = setInterval(function () {
$('#cancion').load('sonando.php?emisora=' + station);
}, 5000);
}

For people who only needs to destroy or stop a previous setInterval, not exactly what the question ask (jquery, song, etc)
const previousSetIntervalInstance = setInterval(myTimer, 1000);
//every 1 second update the time
function myTimer() {
  const date = new Date();
  document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}
function myStopFunction() {
  clearInterval(previousSetIntervalInstance);
}
<h3>setInterval() and clearInterval() demo</h3>
<p id="demo"></p>
<button onclick="myStopFunction()">Stop the time</button>
Initial source: https://www.w3schools.com/jsref/met_win_clearinterval.asp
When you click on stop the time is not updated anymore
Basically, you need to store the setInterval output as global variable and pass it to clearInterval

Related

way too keep function that called by event listener in execution

i try to make a button that get the time now ,put it in element and updated every one second using the event listener the problem that the time disappear immediately
var time
function updateTime(){
time = new Date().toLocaleTimeString();
document.getElementById('showtime').innerHTML=time
setInterval(updateTime, 1000);
}
document.getElementById("btnclock").addEventListener("click", updateTime);
html
<button id="btnclock"> Start Clock</button>
<p id='showtime'> </p>
Update can call setInterval(), but, as others have pointed out, we only want at most one interval timer running. This can be expressed tersely with a nullish coalescing assignment (not so tersely named).
Below, once the intervalID has been initialized, the setInterval() will no longer be evaluated. Keeping the interval id around is useful because it allows for a stop button, also demonstrated...
let intervalID;
function updateTime(run) {
document.getElementById('showtime').innerHTML = (new Date()).toString()
intervalID ??= setInterval(updateTime, 1000);
};
document
.getElementById("btnclock")
.addEventListener("click", updateTime);
document
.getElementById("btnclock-stop")
.addEventListener("click", () => {
clearInterval(intervalID)
intervalID = null; // so the setInterval assignment can run
});
<button id="btnclock"> Start</button>
<p id='showtime'>&nbsp</p>
<br/>
<button id="btnclock-stop"> Stop</button>
The issue is that when you click the button, updateTime function calls setInterval(updateTime, 1000) which creates a timer. The timer calls updateTime function every second. But updateTime creates another timer while the first one is still running. So in fact what is happening is that every second every running timer creates a new timer so after 10 seconds you will have 1024 timers running at the same time. This is obviously not what you want.
Try something like this:
var timer = 0;
function startTimer() {
if (!timer) {
timer = setInterval(updateTime, 1000);
}
}
function stopTimer() {
clearInterval(timer);
timer = 0;
}
function updateTime() {
var time = new Date().toLocaleTimeString();
document.getElementById("show-time").innerHTML = time;
}
document.getElementById("start-clock").addEventListener("click", startTimer);
document.getElementById("stop-clock").addEventListener("click", stopTimer);
<button id="start-clock">Start Clock</button>
<button id="stop-clock">Stop Clock</button>
<p id="show-time"></p>
It is important to destroy the timer when you no longer need it. Function clearInterval does it.

Javascript timer - How do I prevent the timer from speeding up each time .deck is clicked?

I am building a memory card game. the class .deck represents a deck of cards. Each time I click a card the timer speeds up. How do I prevent the timer from speeding up?
function startTimer() {
$(".deck").on("click", function () {
nowTime = setInterval(function () {
$timer.text(`${second}`)
second = second + 1
}, 1000);
});
}
You start multiple intervals, one each click. You probably should just start one. If you want to start it for the first card that is clicked:
function startTimer() {
// Maybe remove old timer? Should happen somewhere in your code.
// Possibly "stopTimer" if you have such a function.
clearInterval(nowTime);
let started = false;
$(".deck").on("click", function () {
if (started) return;
nowTime = setInterval(function () {
$timer.text(`${second}`)
second = second + 1
}, 1000);
started = true;
});
}
That code should have some more cleanup, though. Otherwise you accumulate a lot of dead event listeners.
(Furthermore, i believe that jQuery should never be used.)
You need to stop the previous timer before starting a new one because, if you don't, you wind up with multiple timer callback functions all executing one immediately after the other, which gives the illusion that your single timer is speeding up.
function startTimer() {
$(".deck").on("click", function () {
clearInterval(nowTime); // Stop previous timer
nowTime = setInterval(function () {
$timer.text(`${second}`);
second = second + 1;
}, 1000);
});
}
Another way to deal with this is to only allow the click event callback to run the very first time the button is clicked:
function startTimer() {
$(".deck").on("click", timer);
function timer() {
nowTime = setInterval(function () {
$timer.text(`${second}`);
second = second + 1;
}, 1000);
$(".deck").off("click", timer); // Remove the click event handler
}
}

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>

Stop JavaScript after execution

How do I stop JavaScript after execution?
I create one javascript for post in chat one text if other people say a keyword.
But the script send the message and not stop.
Now the code:
setInterval(function() {
jQuery('#frame_chatbox')
.replaceWith('<iframe id="framejqs" src="/chatbox" scrolling="yes" width="100%" height="100%" frameborder="0"></iframe>');
jQuery('#framejqs').contents()
.find('#chatbox_footer #chatbox_messenger_form #submit_button')
.click(function() {
if(jQuery('#framejqs').contents()
.find('#chatbox_footer #chatbox_messenger_form input[name="message"]')
.val().indexOf('HERE THE KEYWORD') != -1) {
$.post('/chatbox/chatbox_actions.forum?archives',
{mode:"send", sent:"HERE THE MENS"});
return false;
}
});
});
http://pastebin.com/5KF9R5Rv
It sends the message repeatedly because the sending function is wrapped in an interval firing once per millisecond (the second argument is missing):
setInterval(function () {
// ...
}, time_between_sends);
The time_between_sends defines how much time passes by between different calls of the function you passed into setInterval as first argument.
For example:
setInterval(function () {
console.log(new Date()); // logs the date once per second (1000ms === 1s)
}, 1000);
More generally, I'd consider using an event listener instead of an interval though.
You can simply use clearInterval
var interval = setInterval(function() {
//your code
if(condition to stop interval)
{
clearInterval(interval);//clearing interval when you want
}
});
Here is Live Demo
Update
If you want to stop it after you got response from post method you can do something like following:
DEMO
Code:
var myVar = setInterval(function(){
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
$.post('/echo/html/','',function(){
myStopFunction()//calling method to stop setInterval
});
}, 1000);
function myStopFunction() {
alert("stoping");
clearInterval(myVar);
}

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