I am using setInterval(); function to run a function every 5 sec, but i want to clear this interval if
some condition satisfied.
function do_the_job(){
//some code
if(some_condition)
{
clearInterval(interval);
}else{
clearInterval(interval);
var interval = setInterval(do_the_job(),5000);
}
}
function clearInterval(); is not working here.
In your code the var interval =... is local, not visible outside the scope of the function call, and thus will not work in a recursive function.
Make the interval a global variable, and it will work.
solution
var interval;
function do_the_job(){
//some code
if(some_condition)
{
clearInterval(interval);
}else{
clearInterval(interval);
interval = setInterval(do_the_job(),5000);
}
}
Make interval a global or 'higher scoped' variable by moving its declaration outside the if statements, so that it's actually in scope when clearing.
This is not a good time to use setInterval(), try setTimeout() instead
function do_the_job(){
//some code
if(some_condition)
{
// job done
}else{
setTimeout(do_the_job,5000);
}
}
var interval = setInterval(do_the_job(),5000);
Should be no parethesees
var interval = setInterval(do_the_job,5000);
Related
I want this timer to count down from 20 and stop at 0. timerFunction() is called on the click of a button.
var time=20;
var clicked=false;
function timeDisplay(){
document.getElementById("timer").innerHTML=
time;
}
function timerFunction(){
if(!clicked){
clicked=true;
if(time>0){
var i=setInterval(function(){
time--;
timeDisplay();
},1000);
}
else{
clearInterval(i);
}
}
}
Right now, the timer works, but it doesn't stop at zero and I don't understand why. Obviously I am very new to this, so any constructive criticism is appreciated.
Firstly your timerFunction is run only once. The statement if(time>0) will execute only once and it will always be true because time is 20 initially.
You ideally want your time variable to be checked after regular intervals. Something you can do inside your timeDisplay function. To enable that, you need to ensure that unique interval id (here intervalName) can be accessed by timeDisplay.
var time=20;
var clicked=false;
var intervalName = null;
function timeDisplay(){
document.getElementById("timer").innerHTML=
time;
if(time == 0){
clearInterval(intervalName);
}
}
function timerFunction(){
if(!clicked){
clicked=true;
intervalName = setInterval(function(){
time--;
timeDisplay();
},1000);
}
}
Note: I have replaced i with intervalName.
Your code has a logic flaw. When you call timerFunction, you set the interval. But since that function is run only once, it will never check your if clause and it also doesn't set the intervall multiple times, as it would have, would it get executed more than once.
Hint: try to check for the time inside the setIntervall callback. I'm not 100% sure, but you can probably clear the intervall inside aswell with something like clearIntervall(this). Maybe you wanna try this out. :)
Actually your if condition is checking for once and when the execution goes inside if it is not checking if condition again so you should have a condition inside interval function checking the value of time variable and clear interval.
`
var time=20;
var clicked=false;
function timeDisplay(){
document.getElementById("timer").innerHTML= time;
}
function timerFunction(){
if(!clicked){
clicked=true;
var i= setInterval(function(){
time--;
if(time == 0){
clearInterval(i);
}
timeDisplay();
},1000);
}
}
`
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 ...
I have a function called "showCustomer" that get number between 1-5 and return something.
I want to use setInterval, to run this function every 5 second but with another number.
Its not working, i don't understand why its not working to me. here is the code.
setInterval(function () {
var i = 1;
showCustomer(i);
i++;
}, 5000);
Just move the declaration of variable i before the setInterval() call:
var i = 1;
setInterval(function () {
showCustomer(i);
i++;
}, 5000);
The anonymous function you've set as a callback for setInterval gets called every 5 seconds in your code. In every call, you're setting i to 1 which resets it every time.
Moving i outside the setInterval callback makes it persist the the current value.
Every time you use var, you redeclare the value of that variable. So you only should declare the counter one time.
Every time that the browser calls the callback showCustomer the if statement evaluates if the browser should make a new call.
clearInvertal() it's the method to stop the setInterval() method.
var id = 1;
var show5times = window.setInterval(showCustomer, 5000);
function showCustomer() {
alert(id);
id++;
if(id > 5) {
window.clearInterval(show5times);
}
}
I think im missing something fairly obvious with how the clearInterval method works.
So with the code below. I would expect the first function call to execute testFunction and set the interval to repeat the function. The 2nd call would execute the second function which will remove the interval from the 1st function. As this would execute far before the 5000ms interval the first function would not be executed again. However it does not behave like this.
Could someone please explain what is wrong with my method?
Reason for this is in a program I am writing I am making repeated get requests, every 30 seconds or so , using setTimeout but i would like a method to easily remove this interval at other points in the program
function testFunction() {
$("#test").append("test");
setTimeout(testFunction, 5000);
}
function stopFunction() {
clearTimeout(testFunction);
}
testFunction();
stopFunction();
setTimeout returns an ID so you should
var timeoutID = setTimeout(blah blah);
clearTimeout(timeoutID);
setTimeout returns an object that you need to pass into the clearTimeout method. See this article for an example: http://www.w3schools.com/jsref/met_win_cleartimeout.asp
setTimeout returns an identifier for the timer. Store this in a variable like:
var timeout;
function testFunction(){
...
timeout = setTimeout(testFunction, 5000);
}
function stopFunction(){
clearTimeout(timeout);
}
Here is a simple and I think better implementation for this .
var _timer = null,
_interval = 5000,
inProgress = false,
failures = 0,
MAX_FAILURES = 3;
function _update() {
// do request here, call _onResolve if no errors , and _onReject if errors
}
function _start() {
inProgress = true;
_update();
_timer = setInterval(_update, _interval);
}
function _end() {
inProgress = false;
clearInterval(_timer);
}
function _onReject(err) {
if (failures >= MAX_FAILURES) {
_end();
return false;
}
_end();
failures++;
_start();
}
function _onResolve(response) {
return true;
}
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.