Wait until variable equals - javascript

I am trying to check if a variable is equal to 1 using javascript...
myvalue = 1;
function check() {
if (myvalue == 1) {
return setTimeout(check, 1000);
}
alert("Value Is Set");
}
check();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am planning on adding a delay to the setting of the variable but for now why is this simple version not working?

Using setTimeout(check, 1000); calls the function only once. That's not what you are looking for.
What you're looking for is setInterval which executes a function every n miliseconds.
Look at the below example which waits for the value to be 1, using setInterval, and then clearing the setInterval instance once it does.
Wait 4 seconds when running the snippet below:
// First - set the value to 0
myvalue = 0;
// This variable will hold the setInterval's instance, so we can clear it later on
var interval;
function check() {
if (myvalue == 1) {
alert("Value Is Set");
// We don't need to interval the check function anymore,
// clearInterval will stop its periodical execution.
clearInterval(interval);
}
}
// Create an instance of the check function interval
interval = setInterval(check, 1000);
// Update the value to 1 after 4 seconds
setTimeout(function() { myvalue = 1 }, 4000);

Related

How to use setInterval to trigger a function so that I can stop it at some point?

So from what I have understood, setInterval() is used to call a function on repeat on regular intervals.
So basically it is a loop that executes a function forever periodically.
I am confused as to if I had to stop this execution at one point what would be the way to do it
for eg I am trying to print the message "hey" 3 times after 1 second each, but somehow it is printing it 3 times every second and is going on forever.
What can I do to stop it after a set number of times.
This is the code that I've been trying
var i = 3;
function message() {
console.log("hey");
}
while(i > 0) {
setInterval(message, 1000);
i = i - 1;
}
Your code is executing the setInterval thrice in the while loop, which is not needed.
Actually, setInterval does not work as a function call but actually registers a function to be called at some interval.
The setInterval() method will continue calling the function until clearInterval() i.e it is deregistered or the process is killed.
It should work like this
var i = 3;
var interval = setInterval(message, 1000);
function message() {
if (i === 0) {
clearInterval(interval);
}
console.log("hey");
i = i - 1;
}
To clear a setInterval, use global clearInterval method.
Example:
var timerId = setInterval(func, 500);
.... some code here....
clearInterval(timerId);
What can I do to stop it after a set number of times.
usually you don't use setInterval() for this, you use setTimeout().
Something like
var counter = 0;
function message() {
console.log("hey");
// we trigger the function again after a second, if not already done 3 times
if (counter < 3) {
setTimeout(message, 1000);
}
counter++;
}
// initial startup after a second, could be faster too
setTimeout(message, 1000);
The setInterval function calls the function indefinitely, whereas setTimeout calls the function once only.
Simply use clearInterval once the count runs out.
var i = 3;
function message(){
console.log("hey");
if (--i < 0) {
clearInterval(tmr);
}
}
var tmr = setInterval(message, 1000);
you have to assign that setInterval to a javascript variable to name it what for this setInterval, like this
var messageLog = setInterval(message, 1000);
After, in setInterval message function add this condition to clear the inverval whenever you want to clear.
function message(){
if(i>3) {
clearInterval(messageLog); // clearInterval is a javascript function to clear Intervals.
return null;
}
console.log("hey");
}
You can retrieve the timer when creating and clear it if needed.
var i=3;
var timer = setInterval(message,1000);
function message(){
console.log("hey");
iā€”-;
if(i==0)
clearInterval(timer)
}
a beginner here too,look for clearInterval method ...

how to stop the setTimeout recursion

I have created the setTimeout which has a callback named run, Inside the run I have called a console.log(i) to print the value of I with i++ and once it reaches to 50, I want to clear the setTimeout with clearTimeout, I am calling setTimeout again with run making it recursive, but it doesn't work.
can somebody help me understand the concept better?
let i = 1;
var abc = setTimeout(function run(){
console.log(i);
if(i==50){
abc1();
}
i++;
setTimeout(run,100);
},100);
function abc1(){
clearTimeout(abc);
}
When you call setTimeout you get the ID of the timer returned. It's exactly what you've done here:
var abc = setTimeout(function run(){
However, that ID is valid only until the delayed function executes. Once it does, it's ineffective. When you call setTimeout(run,100); you will get a new ID for the timer. You need to capture that again, otherwise the ID gets lost and you have no way to stop it.
There is a final consideration - with your current code even if you were to correctly capture the ID calling abc = setTimeout(run, 100); that would still not stop the counter because it will attempt to stop the function that is running right now (which does nothing), instead of cancelling the execution of the next one:
let i = 1;
var abc = setTimeout(function run() {
console.log(i);
if (i == 50) {
abc1(); //this will clear the *current* timer
}
i++;
abc = setTimeout(run, 100); //this will set the *new* ID
}, 100);
function abc1() {
clearTimeout(abc);
}
In order to stop the execution you have two options. If you want to use your initial idea, you need to cancel the future execution after it is scheduled
let i = 1;
var abc = setTimeout(function run() {
console.log(i);
abc = setTimeout(run, 100); //this will set the *new* ID
if (i == 50) {
abc1(); //this will clear the *new* timer now
}
i++;
}, 100);
function abc1() {
clearTimeout(abc);
}
Alternatively, you can do it without using timer handles at all and just use the if condition to determine if you want to schedule another execution or not:
let i = 1;
setTimeout(function run() {
console.log(i);
if (i != 50) { //until 50 is reached
abc = setTimeout(run, 100); //schedule a new execution
}
i++;
}, 100);
The problem is the order of your operations.
if(i==50){
abc1();
}
If i reaches 50, the function abc1() will be called - which clears the interval.
i++;
setTimeout(run,100);
here you're restarting the interval.
You need to wrap it inside an else block.
let i = 1;
var abc = setTimeout(function run() {
console.log(i);
if (i == 50) {
abc1();
} else {
i++;
setTimeout(run, 100);
}
}, 100);
function abc1() {
clearTimeout(abc);
}
let i = 1;
var abc = setTimeout(function run(){
console.log(i);
if(i<50){
setTimeout(run,100);
}
i++;
},100);
You should run timeout only if timer not run out.
The setTimeout() inside run() in not assigned to any variable so it can't be cleared in any manner.
I suppose what you want is to overwrite abc so you must replace:
setTimeout(run,100);
by
abc = setTimeout(run,100);
Since var abc is only set once, at the first timeout, you are clearing only the very first Timeout, which very likely is already complete.
SetTimeout returns a numeric value, which is an ID to refer to that task. When you call clearTimeout, you must inform the ID of the timeout you want to clear, and now you are informing the ID for the very first timeout, which is already finished, thus can't be cleared.
If you wish to clear the last timeout, maybe you would like to always update abc with the IDs for each timeout, like this:
abc = setTimeout(run,100);
This is a weird way of doing a timed loop but you just need to clear (actually not in this case but I like to do it anyway as it is a good practice to release resources once you don't use them anymore) the timeouts (done by keeping track of abc handle) before creating new ones and return after clear on the given condition:
let i = 1;
let abc = setTimeout(
function run(){
console.log(i);
if(i==50){
abc1();
return;
}
abc1();
i++;
abc = setTimeout(run,100);
},
100
);
function abc1(){
clearTimeout(abc);
}
you need to add return after you call abc1 function. you clear timeout, but then code still running and call setTimeout(run,100) again.
let i = 1;
var abc = setTimeout(function run(){
console.log(i);
if(i==50){
abc1();
return;
}
i++;
setTimeout(run,100);
},100);
function abc1(){
clearTimeout(abc);
}

Unable to clear interval

I want to terminate the interval created with setInterval if the count goes to 3.
I tried the code below but it is not calling the alert inside the if block. Why? Is my comparison not correct or is something else wrong?
$(window).load(function() {
var timerId = 1;
timerId = window.setInterval(function() {
timerId = timerId + 1;
if(timerId == '3') {
alert(timerId);
clearInterval(timerId);
}
}, 2000);
});
Try not using the same variable for everything
$(window).load(function() {
var timerNum = 1,
timerId = window.setInterval(function(){
timerNum++;
if( timerNum == 3 ){
clearInterval(timerId);
}
}, 2000);
});
You can't use the same variable for the count and the interval, the count is something you update yourself adding 1 every time the callback in the interval executes, while the setInterval function returns a unique ID that can later be passed to clearInterval to clear that specific interval, and by overwriting that ID with your number the unique ID is lost, and the interval can no longer be cleared.
$(window).load(function() {
var timerId =1;
timerCount = window.setInterval(function(){
timerId=timerId+1;
if(timerId=='3'){ alert(timerId); clearInterval(timerCount);}
}, 2000); });
You have two variables with the same name, change one of the variables names to avoid them 'clashing'.
You are using same variable for storing an integer value and unique interval ID return by window.setInterval. So use different variables , that may fix your problem
$(window).load(function() {
var timerId =1;
var intId = window.setInterval(function(){
timerId=timerId+1;
if(timerId=='3'){ alert(timerId); clearInterval(intId);}
}, 2000); });

Javascript: Force new loop iteration in setInterval

I have a setInterval loop. It's set to 3500 milliseconds, like so:-
var loop = setInterval(function() { /*stuff*/ }, 3500);
At one point in 'stuff' if a certain situation occurs, I want to force a new iteration of the loop and NOT WAIT for the 3500 milliseconds. How is that possible? Is it continue or do I just need to frame the process differently?
You could try writing an anonymous self-calling function using setTimeout instead of setInterval:
var i = 0;
(function() {
// stuff
i++;
if (i % 2 == 0) {
// If some condition occurs inside the function, then call itself once again
// immediately
arguments.callee();
} else {
// otherwise call itself in 3 and a half seconds
window.setTimeout(arguments.callee, 3500);
}
})();ā€‹ // <-- call-itself immediately to start the iteration
UPDATE:
Due to a disagreement expressed in the comments section against the usage of arguments.callee, here's how the same could be achieved using a named function:
var i = 0;
var doStuff = function() {
// stuff
i++;
if (i % 2 == 0) {
// If some condition occurs inside the function, then call itself once again
// immediately
doStuff();
} else {
// otherwise call itself in 3 and a half seconds
window.setTimeout(doStuff, 3500);
}
};
doStuff();
You can use something like this... using setTimeout instead of setInterval...
<script type="text/javascript">
var show;
var done = false;
show = setTimeout(showHideForm, 3500);
function showHideForm() {
// Do something
if(done) {
clearTimeout(show);
show = setTimeout(showHideForm, 2000);
}
}
</script>
clearTimeout takes as argument the handle which is returned by setTimeout.
Use a named function and call it when you want.
var loop = setInterval(loopFunc, 3500);
function loopFunc(){
//do something
}
function anticipate(){
clearInterval(loop); //Stop interval
loopFunc(); //Call your function
loop = setInterval(loopFunc, 3500); //Reset the interval if you want
}
My contrived example:
var time = 3500,
loops = 0,
loop;
(function run(){
var wait = time,
dontwait = false;
if (loops++ == 5) {
loops = 0;
dontwait = 1000;
}
console.log('Interval: ', dontwait || wait);
return loop = setTimeout(run, dontwait || wait);
})();ā€‹
http://jsfiddle.net/NX43d/1/
Basically, a self-invoking function looping back on a self-calling function, with (!) shorthand variable switching. Nifty.
function looper(t) {
var loop = setInterval(function() {
document.write(s++);
if (mycondition) { // here is your condition
loopagain(200); // specify the time which new loop will do
loop = window.clearInterval(loop); // clear the first interval
return; // exit from this function!
}
}, t);
}
window.onload = looper(1000); // this will have default setInterval function time ans will start at window load!
function loopagain(t) {
looper(t);
}ā€‹
http://jsfiddle.net/tFCZP/

clearTimeout in closures

I have created a jquery plugin with following structure:
(function($){
var timer_handle, i = 5 ;
$.my_plugin = function(){
return{
// provide $.my_plugin.reset() public method to reset
reset : function(){ clearTimeout(timer_handle); }
}
}();
$.fn.my_plugin = function(){
// init codes ...
function tick(){
i -= 1;
console.log(i+'sec elapsed');
if(i == 0){
console.log('time over');
$.my_plugin.reset();
}
timer_handle = setTimeout(tick, 1000);
}
tick();
}
})(jQuery);
$('body').my_plugin();
When I see at console , after 0 sec elapsed, the counter is still running in negative,
ie the setTimeout has not been cleared.
As I examined , the public method
$.my_plugin.reset(); called from outside clear the timer,
but $.my_plugin.reset() called inside tick closure do not clear timer.
What may be the solution for such case ?????
Because you're calling $.my_plugin.reset(); from inside the tick() function there is no timeout to clear. The previously scheduled timeout has already happened and that's why tick() is executing. (This has nothing to do with whether the code is in a closure or not.)
Instead, just don't set the next timeout if i has reached 0:
function tick(){
i -= 1;
console.log(i+'sec elapsed');
if(i == 0){
console.log('time over');
} else {
timer_handle = setTimeout(tick, 1000);
}
}
If you were to call $.my_plugin.reset(); from some other code outside tick() then there would be an outstanding timeout that could be cleared so it would stop tick() running again.
Note that declaring your timer_handle and i variables in that immediately invoked anonymous function means that all calls to your plugin will access those same variables so you will get incorrect behaviour if you run your plugin against more than one element on the page at the same time.

Categories

Resources