Jquery - looping with nested functions and setInterval() - javascript

Probably not the clearest title, but here goes - I need to display two independent countdowns on a page, accepting a user input for the starting value for each. When one reaches zero, the other starts and counts down to zero. Code for this is below, and working as expected.
I call the Timer1 function, which checks a variable for the starting value, if it exists, the count starts. When the count is zero, I clear the interval, reset the display to the starting value, and fire the second timer, if it has a value assigned:
function Timer1() {
var gDuration = goTime;
countdown = setInterval(function () {
if (gDuration >= 0) {
$("#durationValue").html(ToTime(gDuration));
gDuration--;
}
else {
clearInterval(countdown);
$("#durationValue").html(ToTime(goTime));
if (restTime != 0) {
Timer2();
}
}
}, 1000);
}
function Timer2() {
var rDuration = restTime;
countdown = setInterval(function () {
if (rDuration >= 0) {
$("#restValue").html(ToTime(rDuration));
rDuration--;
}
else {
clearInterval(countdown);
$("#restValue").html(ToTime(restTime));
}
}, 1000);
}
The next step is to allow that process to run for a set number of loops - I've tried wrapping setInterval in Timer1 in a for loop, which doesn't work. Any ideas how to better go about this?

for-loops don't work well with asynchronous stuff. Just make it a counter with an end condition as you have demonstrated with g/rDuration already.
With some callback abstractions, and heavy continuation-passing-style:
function timer(el, duration, interval, callback) {
var countdown = setInterval(function() {
if (duration-- >= 0) {
el.text(ToTime(duration));
} else {
clearInterval(countdown);
callback();
}
}, interval);
}
var goTime = …, restTime = …;
function t1(cb) {
timer($("#durationValue"), goTime, 1000, cb);
}
function t2(cb) {
timer($("#restValue"), restTimer, 1000, cb);
}
var loops = …;
(function loop(cb) {
t1(function(){
t2(function() {
if (loop-- >= 0)
loop(cb);
else
cb();
});
});
})(function() {
alert("finished!");
});

The easiest thing I can think of is to have your Timer functions have a parameter with the current iteration. Increment that value whenever one timer starts another time. And use that value to determine if it should indeed start the next timer.

Related

How to use the clearInterval() function to us?

Cannot terminate the setInterval I created in launch. It works until the time is up. I want to use clearInterval (interval) operation in next() function and prev() function. How should I do this? When I click forward, I want clearInterval(interval) to run this, but I couldn't.
function launch() {
thisTimeline = document.getElementsByClassName('story-active-' + start)[0];
var maxtime = 5000;
var incremental = 100;
var actualtime = 0;
var interval = setInterval(function() {
actualtime += incremental;
var percentage = Math.ceil((100 / maxtime) * actualtime);
thisTimeline.style.width = percentage + '%';
if (percentage == 100) {
clearInterval(interval);
thisTimeline.style.width = "0%";
}
}, incremental);
}
function next() {
// Set previous video timeline to 100% complete
thisTimeline.style.width = '100%';
// Advance play count to next video
start++;
// If next video doesn't exist (i.e. the previous video was the last) then close the Social Story popup
if (start >= defaults.playlist.length) {
setTimeout(function() {
close();
return false;
}, 400);
} else {
// Otherwise run the next video
launch(start);
}
}
function prev() {
if (start != 0) {
thisTimeline.style.width = '0%';
}
// Subtract play count to previous video
start--;
// If next video doesn't exist (i.e. the previous video was the last) then close the Social Story popup
if (start < 0) {
start = 0;
return false;
} else {
// Otherwise run the previous video
launch(start);
}
}
This is an extension of #lagoCalazans comment.
What he is saying is that in your variable "interval" is created in your launch function. You need to make "interval" global in order to clear your setInterval.
Ex:
let interval = null; //global
function launch() {
let tempInterval = setInterval(function() {
//whatever code
},100);
interval = setInterval(function(){
console.log("Hello");
}, 100);
}
function clear() {
//Since interval is global I can clear it when I call clear();
clearInterval(interval);
}
As you can see in the launch function "tempInterval" is limited to the scope of launch, therefore cannot be accessed anywhere else, but now since "interval" is global it can be accessed in any function.
Your code seems a bit incomplete, so for illustrative purposes only I will assume you encapsulate those functions in a higher order function (like an IIFE) and will avoid writing that (also, some kind of global state or variable would do for an example).
First of all, setInterval will return an id which you would use later, so if you want to use it within next and prev, you need that value to be available to them.
So, in your example, you should declare interval outside launch, and assign a value to it inside:
let interval
function launch() {
// ...
interval = setInterval(function() { ... })
}
and then use interval wherever you want.
launch, next and prev are three separate functions. They do not reference the same interval because they don't share scope. Raise the scope of the interval variable.
let interval = ''; // declared here, interval can be accessed by all functions
function launch() {
// ...
// remove the var before interval
interval = setInterval( ... )
}
function next() {
// ...
// remove the var before interval
interval = setInterval( ... )
}
function prev() {
// ...
// remove the var before interval
interval = setInterval( ... )
}

Using setInterval to Save Form Every 60 Seconds Not Working

I'm working on some code that'd I'd like to have each loop run every 60 seconds, but currently each loop runs immediately. The purpose of the code it to see if a form has changed, and if it has save the form. Do I have setInterval setup incorrectly?
function saveHelper(formId) {
for(var i = 0; i < 4; i++) {
save(formId);
}
}
function save(formId) {
console.log('might save');
var changed = formChanges(formId);
var intId = setInterval(stall, 60000);
if(changed.length > 0) {
console.log('would save');
//document.getElementById(formId).submit();
}
clearInterval(intId);
}
function stall() {
return true;
}
You are treating interval as some sort of synchronous sleep method, which is not the case. The change code should be inside of the setInterval, it should not live after the interval.
var intId = setInterval(function () {
if(changed.length > 0) {
console.log('would save');
//document.getElementById(formId).submit();
}
}, 60000);
setInterval doesn't pause your code, it just schedules some code to be run some time in the future. For example, when you do this:
var intId = setInterval(stall, 60000);
That says "every 60000 milliseconds, run the function stall". As soon as this line of code completes, it will immediately run your next line of code, do the saving, then clear the interval. Clearing the interval cancels it, so now nothing will happen in 60000 milliseconds.
Instead, you'll want to do something like this:
function saveHelper(formId) {
let count = 0;
const intId = setInterval(function () {
if(changed.length > 0) {
console.log('would save');
//document.getElementById(formId).submit();
}
count++;
if (count === 4) {
clearInterval(intId);
}
}, 60000);
}
Every 60000 milliseconds, the inner function will run, and do the saving. After saving, it checks how many times we've done this, and once it reaches 4, it clears the interval to stop it from happening any more.

Javascript: Multiple timers VS single timer

I have a simple question about Javascript timers and their performance but it really bugs me because I can't figure out the right way to do it.
Here is the problem: I have a special timing function that self corrects itself:
function setCorrectingInterval(func, delay) {
if (!(this instanceof setCorrectingInterval)) {
return new setCorrectingInterval(func, delay);
}
var target = Date.now() + delay;
var self = this;
function tick() {
if (self.stopped) {
return;
}
target += delay;
func();
setTimeout(tick, target - Date.now());
}
setTimeout(tick, delay);
}
Then, in my application I use this function n times to set n different timer variables. So if I have two timer variables I would use this function twice to set them. In the code bellow I execute first task every 1000ms and second task every 2000ms:
var firstTimer,
secondTimer;
function startFirstTimer() {
firstTimer = setCorrectingInterval(function() {
console.log("First!");
}, 1000);
}
function startSecondTimer() {
secondTimer = setCorrectingInterval(function() {
console.log("Second!");
}, 2000);
}
startFirstTimer();
startSecondTimer();
In my angular application the need for multiple timing events grows and grows. So my (tempoprary) solution to this is to create new timer variables with new setTimeouts using the setCorrectingInterval function as mentioned above.
So I got thinking - wouldn't it be better (performance wise) to just have one single timer variable with one single setTimeout in which using if statements I would execute tasks that meet the condition, like this:
var timer;
function startTimer() {
var counter = 1;
timer = setCorrectingInterval(function() {
console.log("First!");
if (counter % 2 === 0) {
console.log("Second!");
}
counter++;
}, 1000);
}
startTimer();
( provided every tasks would repeat execution with delay that is multiple of 1000 )
Which approach is better and why? Any explanation is very much appreciated, thank you

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

Is there a way to check if a var is using setInterval()?

For instance, I am setting an interval like
timer = setInterval(fncName, 1000);
and if i go and do
clearInterval(timer);
it does clear the interval but is there a way to check that it cleared the interval? I've tried getting the value of it while it has an interval and when it doesn't but they both just seem to be numbers.
There is no direct way to do what you are looking for. Instead, you could set timer to false every time you call clearInterval:
// Start timer
var timer = setInterval(fncName, 1000);
// End timer
clearInterval(timer);
timer = false;
Now, timer will either be false or have a value at a given time, so you can simply check with
if (timer)
...
If you want to encapsulate this in a class:
function Interval(fn, time) {
var timer = false;
this.start = function () {
if (!this.isRunning())
timer = setInterval(fn, time);
};
this.stop = function () {
clearInterval(timer);
timer = false;
};
this.isRunning = function () {
return timer !== false;
};
}
var i = new Interval(fncName, 1000);
i.start();
if (i.isRunning())
// ...
i.stop();
The return values from setTimeout and setInterval are completely opaque values. You can't derive any meaning from them; the only use for them is to pass back to clearTimeout and clearInterval.
There is no function to test whether a value corresponds to an active timeout/interval, sorry! If you wanted a timer whose status you could check, you'd have to create your own wrapper functions that remembered what the set/clear state was.
I did this like below, My problem was solved. you should set the value like "false", when you clearTimeout the timer.
var timeer=false;
----
----
if(timeer==false)
{
starttimer();
}
-----
-----
function starttimer()
{
timeer_main=setInterval(activefunction, 1000);
timeer=true;
}
function pausetimer()
{
clearTimeout(timeer_main);
timeer=false;
}
Well you can do
var interval = setInterval(function() {}, 1000);
interval = clearInterval(interval);
if (typeof interval === 'undefined'){
...
}
but what are you actually trying to do? clearInterval function is an always success function and it will always return undefined even if you call it with a NaN value, no error checking in there.
You COULD override the setInterval method and add the capability to keep track of your intervals. Here is an untestet example to outline the idea. It will work on the current window only (if you have multiple, you could change this with the help of the prototype object) and this will only work if you override the functions BEFORE any functions that you care of keeping track about are registered:
var oldSetInterval = window.setInterval;
var oldClearInterval = window.clearInterval;
window.setInterval = function(func, time)
{
var id = oldSetInterval(func, time);
window.intervals.push(id);
return id;
}
window.intervals = [];
window.clearInterval = function(id)
{
for(int i = 0; i < window.setInterval.intervals; ++i)
if (window.setInterval.intervals[i] == id)
{
window.setInterval.intervals.splice(i, 1);
}
oldClearInterval(id);
}
window.isIntervalRegistered(id)
{
for(int i = 0; i < window.setInterval.intervals; ++i)
if (window.setInterval.intervals[i] == func)
return true;
return false;
}
var i = 0;
var refreshLoop = setInterval(function(){
i++;
}, 250);
if (isIntervalRegistered(refrshLoop)) alert('still registered');
else alert('not registered');
clearInterval(refreshLoop);
if (isIntervalRegistered(refrshLoop)) alert('still registered');
else alert('not registered');
The solution to this problem: Create a global counter that is incremented within your code performed by setInterval. Then before you recall setInterval, test if the counter is STILL incrementing. If so, your setInterval is still active. If not, you're good to go.

Categories