Temporary changing the time of setInterval - javascript

The timing value in setInterval determines the next time at which the function is going to be invoked again. For example:
t = 8000;
myFunction(){
if (someCondition){
//halt setInterval
//t = 5000;
// setInterval(myFunction,t);
}
// do some logic
}
setInterval(myFunction, t);
The problem is changing of t will not affect the time that I want the current call to be remained before the next call. In other words, is there any way to halt setInterval and then I can reset it again with new time?

If you want to do something like that, you're better off doing your own interval control with setTimeout.
var shortInterval = 2000, longInterval = 4000;
function timerCode() {
// do something
if (whatever) {
setTimeout(timerCode, shortInterval);
}
else {
setTimeout(timerCode, longInterval);
}
}
setTimeout(timerCode, longInterval);
That way, on each iteration of the timer you can decide how long it should be until the next iteration. If you want to stop, just don't reset the timer at all.

You have to use clearInterval().
var myInterval = setInterval(myFunction, t);
...
clearInterval(myInterval);
...
myInterval = setInterval(myFunction, 1000);

Related

clearTimeout not working: parameter undefined(even though it's defined in the global scope)

My setTimeout() function works, but my clearTimeout() is not working. Even though I have an 'if' statement that's supposed to run the clearTimeout function once my variable 'secs' is less than 0, the timer keeps counting down into negative numbers. When I type my variable name, 'secs' into the console, I get undefined, even though it's defined as a parameter in the function called by my setTimeout. I don't know what I'm doing wrong. Can anyone help, please?
My full code is at https://codepen.io/Rburrage/pen/qBEjXmx;
Here's the JavaScript snippet:
function startTimer(secs, elem) {
t = $(elem);
t.innerHTML = "00:" + secs;
if(secs<0) {
clearTimeout(countDown);
}
secs--;
//recurring function
countDown = setTimeout('startTimer('+secs+',"'+elem+'")', 1000);
}
Add a condition to call recursive function like below.
if (secs < 0) {
secs = secsInput;
}
//recurring function
countDown = setTimeout('startTimer('+secs+',"'+elem+'")', 1000);
For a countdown timer, I would recommend using setInterval and clearInterval instead. setInterval will repeatedly run the callback function for you. It might look like this:
let countdown;
function startTimer(secs, elem) {
countdown = setInterval(function(){
t = $(elem);
t.innerHTML = "00:" + secs;
secs--
if (secs < 0) {
clearInterval(countdown);
}
}, 1000);
}
By the time you call clearTimeout(countDown), countDown refers to the previous timeout, that already timed out. It will not stop the one yet to start. You could just not re set the timeout, like
if(!/*finished*/) setTimeout(startTimer, 1000, secs, elem);
In your case, it's more convenient to use setInterval and clearInterval.
To keep the setTimeout and clearTimeout functions, you should add return in the if statement.
function startTimer(secs, elem) {
t = $(elem);
t.innerHTML = "00:" + secs;
if(secs<0) {
clearTimeout(countDown);
return;
}
secs--;
//recurring function
countDown = setTimeout('startTimer('+secs+',"'+elem+'")', 1000);
}
So there are 4 events in my opinion that will have to be addressed by the timer:
The quiz starts
The quiz ends
The timer runs out
The player answers a question
This can be solved by a function returning an object with some options.
The createTimer can be used to set the parameters for the timer.
Point 1. would be timer.start() --> will start a timer with the parameters
Point 3. can be addressed with the callback that will be called if the timer runs out --> createTimer(5,'display', ()=>{ // your code goes here })
Point 2. can be achieved with --> timer.stop()
Point 4. is needed when the timer needs to be reset without running out timer.reset()
Further on the interval is not in the global scope so you could have multiple timers with different settings and they wouldn't interfere with each other
// function for creating the timer
function createTimer(seconds, cssSelector, callbackOnTimeout) {
// interval the timer is running
let interval;
// the html node where innerText will be set
const display = document.getElementById(cssSelector)
// original seconds passt to createTimer needed for restart
const initSec = seconds
// starting or continuing the interval
function start() {
// setting interval to the active interval
interval = setInterval(() => {
display.innerText = `00:${seconds}`;
--seconds;
if (seconds < 0) {
// calling restart and callback to restart
callbackOnTimeout()
restart()
}
}, 1000);
}
// just stopping but not resetting so calling start will continue the timer
// player takes a break
function stop(){
clearInterval(interval)
}
// opted for a restart and not only a reset since it seemed more appropriate for your problem
function restart(){
clearInterval(interval)
seconds = initSec
start()
}
// returning the object with the functions
return {
start: start,
stop: stop,
restart: restart
}
}
// example for creating a timer
const timer1 = createTimer(5,'display',()=>{
console.log(`you where to slow ohhh...`)
})
// calling the timer
timer1.start()

Can someone tell me why one of these JavaScript code works and one doesn't?

I want the animation to stop when the number of clicks reach certain number.
Why the first snippet works, and the second one doesn't.
The only difference is where clearInterval is called.
This one works --- stops the animation.
var intervalId = setInterval(moveHeading, intervalLength);
var intervalLength = 120;
var clicks = 0;
$("#heading").click(function () {
clearInterval(intervalId);
clicks++;
intervalLength /= 2;
if (clicks >= 3) {
$("#heading").text("You Win!");
} else {
$("#heading").text(clicks);
intervalId = setInterval(moveHeading, intervalLength);
}
});
However this one one won't work --- doesn't stop animation.
var intervalId = setInterval(moveHeading, intervalLength);
var intervalLength = 120;
var clicks = 0;
$("#heading").click(function () {
clicks++;
intervalLength /= 2;
if (clicks > 3) {
clearInterval(intervalId);
$("#heading").text("You Win!");
} else {
$("#heading").text(clicks);
intervalId = setInterval(moveHeading, intervalLength);
}
});
On the first one, you clearInterval, then overwrite intervalId when you call setInterval, so you will never have a setInterval that is still running, where you no longer know the intervalId.
On the second one, if clicks <= 3, then you will overwrite intervalId, but you never cleared the running setInterval, so it will continue to run, and you will never be able to clearInterval on it since you don't know it's id (you will just be able to clear the interval for whatever new interval you created).
The setInterval() method will execute the function once every 1 second, just like a digital watch.
we have to use clearInterval() to stop the time.
It clears a timer set with the setInterval() method.
You must have to use it, in order to stop your animations.

javascript timer counting very fast as time passes

I want a counter which reset in specific interval of time. I wrote this code. When I refresh the page it is executing perfectly. But as time passes the timer goes really fast, skipping seconds. Any idea why this is happening.
function countdown_new() {
window.setInterval(function () {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter) - eval(1);
$("b[id=show-time]").html(updateTime);
if (updateTime == 0) {
//window.location = ("ajax_chart.php");
$("b[id=show-time]").html(5);
clearInterval(countdown_new());
// countdown_new();
//my_ajax();
}
}, 1000);
}
window.setInterval(function () {
countdown_new();
}, 5000)
HTML
Coundown in 5 seconds
The issue is because you are not clearing the previous timer before starting a new one, so you start a new one for each iteration. To clear the timer you should save a reference to it, and pass that to clearInterval, not a function reference.
Also, note that your pattern of using multiple intervals for different operations can lead to overlap (where two intervals are acting at the same time and cause odd behaviour). Instead, use setTimeout for the initial 5 second delay and then chain further calls to stop this overlap.
Try this:
var timer;
function countdown_new() {
timer = setInterval(function () {
var $showTime = $("#show-time")
var updateTime = parseInt($showTime.text(), 10) - 1;
$showTime.html(updateTime);
if (updateTime == 0) {
$showTime.html('5');
clearInterval(timer);
setTimeout(countdown_new, 5000);
}
}, 1000);
}
setTimeout(countdown_new, 5000);
Example fiddle
Note that you should use the # selector to select an element by its id attribute, and you should never use eval - especially not for type coercion. To convert a value to an integer use parseInt().
You are calling window.setInterval(), which schedules a function call to countdown_new() ever 5 seconds without stop.
Compounding the problem, you are calling countdown_new() again inside your clear interval.
You need to call setInterval just once to continuously execute a function every 5 seconds.
If you want to cancel an interval timer, you need do to this:
var intervalObj = setInterval(function() { ... }, 5000);
clearInterval(intervalObj);
Yes clearinterval does the trick.
function countdown_new(){
t = window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
if(updateTime == 0){
//window.location = ("ajax_chart.php");
$("b[id=show-time]").html(5);
clearInterval(t);
// countdown_new();
my_ajax();
}
}, 1000);
}

Can I stop the execution of a function from outside that function?

I have this code:
function toStop(){
while(true){}
}
toStop();
Now, how can I stop this? Or how can I kill the current thread if this function call is somewhere in the setInterval running thread? Example:
var id = setInterval(function(){
toStop();
}, 1000);
//stop thread/timer with id here.
clearInterval doesn't work because it waits until the function call ends.
Thanks!
"Can I stop the execution of a function from outside that function?"
No, you can't programmatically.
JavaScript is single-threaded and if you run a piece of code that makes it infinitely busy, such as while(true);, then nothing else will ever be able to execute.
Calling such a piece of code within setTimeout or setInterval will have the same result, since the callback of these gets executed in the only thread we have as well.
However, you can create a timed recurring execution using setInterval or setTimeout, which can be stopped.
var timerId = setInterval(function () {
//Process an iteration of the loop in here
//If you cause an infinite loop in here, you will have the same issue
}, 50);
//stop the timer after ~3 seconds
setTimeout(clearInterval.bind(null, timerId), 3000);
Notes:
4 is the lowest interval that could be honored as specified in the SPEC.
setInterval will stack if the callback takes more time to execute than the specified interval. For that reason I never use setInterval and always use setTimeout.
Timer intervals are not guaranteed to be accurate
e.g. with setTimeout
var stopProcessing = startProcessing();
//Stop processing after ~3 seconds
setTimeout(stopProcessing, 3000);
function startProcessing() {
var timerId;
!function process() {
//Do some processing
//Continue processing in ~50 ms
timerId = setTimeout(process, 50);
}();
return function () { clearTimeout(timerId); }
}
Instead of an infinite loop, just use an if statement and wrap it in an interval:
var shouldContinue = true;
var interval = 0;
function toStop() {
if (interval == 0) {
interval = setInterval(function() {
if(shouldContinue) {
...
}
else {
clearInterval(interval);
interval = 0;
}
}, 200); // Or whatever interval makes sense
}
}
toStop();
// ...
shouldContinue = false;
See this principle in action here.
No, you can't programmatically, as #plalx said but you could try this: declaring a binding outside and check on that to continue or stop the loop:
let letMeGoOut;
function toStop(){
while(letMeGoOut != false)
}
toStop();
Here, I've created a function on mouseover that triggers a loop changing the opacity of the h1. It goes on till the mouse cursor moves out and is over something else in the page.
Here is the example: https://codepen.io/Mau-Di-Bert/pen/VqrRxE

How to stop time interval in my function?

I have this function:
function timedFunction(functionString,timeoutPeriod) {
setTimeout(functionString+"timedFunction(\""+functionString+"\","+timeoutPeriod+");",timeoutPeriod);}
This function me call:
timedFunction("startStopky();",1000);
startStopky(); is a function that I want in a specified time interval repeatedly run. Everything works excellently, but if I want stop this interval, I have to stop as follows:
for (var i = 1; i < 99999; i++) {
window.clearInterval(i);
}
Unfortunately this will stop all intervals, and I want to stop just one particular. How can I do it?
Instead of doing recursive calls to timedFunction just do:
var intervalId = setInterval(startStopky, 1000);
and to clear it just do:
clearInterval(intervalId);
The setTimeout function returns a timeout ID that you use with clearTimeout to remove that timeout. The same goes for intervals but in that case it's a setInterval and clearInterval combo.
E.g.:
var t = setTimeout(yourFunction, 1000);
clearTimeout(t);
var i = setInterval(yourFunction2, 500);
clearInterval(i);
You have a Timeout, but you are clearing an Interval. clearInterval clears intervals, not timeouts.
You want window.clearTimeout(timeoutId)
If you want to stop a single one, you use the processId of that interval.
window.clearTimeout("13");
You really shouldn't be using strings to do this:
function timedFunction(fn, interval) {
var timerHandle;
function runIt() {
fn();
timerHandle.id = setTimeout(runIt, interval);
}
return timerHandle = { id: setTimeout(runIt, interval) };
}
Then you can call it like this:
var handle = timedFunction(startStopky, 1000);
To stop the process:
clearTimeout(handle.id);

Categories