Unable to clear interval - javascript

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

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 ...

Wait until variable equals

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

Javascript function setTimeout and setIntervall not working

I've got this Problem here, that this function is not working and I cant figure out why..
This function should count to 10 (in 10 seconds). For this purpose I'm using a for loop with setTimeout function - duration set to 1000ms.
It should go on and on for what i took the setInterval function.
function timer() {
var time=10;
for(i=0; i<time; i++){
setTimeout(console.log(i+1), 1000);
}
}
setInterval(timer, 10000);
The Problem is, that it isnt working and I dont understand why ... I have found another working solution but would like to know the issue of this one. :)
The reason that nothing appears to happen is the way that you use setTimeout. Instead of providing an event handler you are calling console.log and try to use the return value from that call as event handler.
The closest thing that would at least do something would be to make a function that calls console.log:
setTimeout(function(){ console.log(i+1) }, 1000);
However, you will notice that it will just log the value 11 ten times at once, every ten seconds, indefinitely.
Eventhough the loop counts from 0 to 9, you start a timeout in each iteration that will be triggered one second from when it was created. As all ten timeouts are created at the same time, they will be triggered at the same time. There isn't a separate variable i for each handler, so they will all show the value in the variable at the time that they are triggered, and as the loop has completed before any of them can be called they will all show the final value 10 + 1.
You are using both an interval and timeouts, you should use one or the other.
You can start timeouts in a loop, but then you should only do it once, not in an interval, and you should specify the time from start to when you want it to be triggered:
var time = 10;
for (var i = 1; i <= time; i++){
setTimeout(function() { console.log('tick'); }, 1000 * i);
}
If you want to use the variable in the event handler, then you need to create a copy of the variable for each iteration:
var time = 10;
for (var i = 1; i <= time; i++){
(function(copy){
setTimeout(function() { console.log(copy); }, 1000 * i);
})(i);
}
You can use an interval, but then you don't have a loop, it's the interval that is the loop. Use clearInterval to stop it when you reach the end of the loop:
var i = 1, time = 10, handle;
function timer() {
console.log(i);
i++;
if (i > time) clearInterval(handle);
}
handle = setInterval(timer, 1000);
First, it's not working because setTimeout call is wrong. Even if your setTimeout call worked, there's another issue here. Your code will actually print 11 every 10 seconds.
function timer() {
var time = 10;
for (i = 0; i < time; i++) {
setTimeout(function() {
console.log(i + 1)
}, 1000);
}
}
setInterval(timer, 10000);
Because, you have sequential setTimeout calls to be effected every second and you are forming a closure on the variable i.
You need to take care of the closure and calls must be done after the second has been printed.
function timer() {
var p = Promise.resolve();
for (var i = 0; i < 10; i++) {
p = p.then(closure(i));
}
}
function closure(i) {
return (function () {
return new Promise(function (resolve) {
setTimeout(function () {
document.getElementById('results').innerHTML = (i + 1) + '\n';
resolve();
}, 1000);
})
});
}
timer();
setInterval(timer, 10000);
<pre id="results"></pre>
When I run your code in the Firebug debugger, I see:
TypeError: can't convert console.log(...) to string
I added a comment to your code about that error:
function timer() {
var time=10;
for(i=0; i<time; i++){
// The source of error is the line below
// Type error: setTimeout needs a function as first argument!
setTimeout(console.log(i+1), 1000);
}
}
setInterval(timer, 10000);
A corrected version might be
function timer() {
var time=10;
for(i=0; i<time; i++){
setTimeout(function() { console.log(i+1); }, 1000);
}
}
setInterval(timer, 10000);
However, the above change fixes the type error but not the logic.
You probably wanted to do this:
var counter = 0;
var count = function() {
console.log(++counter);
if (counter >= 10) {
clearInterval(timer);
}
};
var timer = setInterval(count, 1000);
Once the callback function count notices the counter passed the value 10 it will stop the periodic timer whose ID was saved in the variable timer when setting it up.

setInterval() not repeating. Works only 1 time

I'm trying to have a div's left property change by its self - one every second when your hovering over so I made this:
$("div.scroll_left").hover(function(){
var left_num = $('div.license_video').css("left")
var left_num1 = parseInt(left_num, 10) - 1;
var timerID = setInterval(alert(left_num1), 1000);
//var timerID = setInterval(slideleft(left_num1), 1000);
},function(){
clearInterval(timerID);
});
//function slideleft(left_num){
//$('.license_video').css('left', left_num + "%");
//}
In theory you would think it repeat till you move your cursor off which clears the interval. When I hover over it does it one time and never repeats (there are no errors). Then when I hover off it gives a error "Uncaught ReferenceError: timerID is not defined"
setInterval isn't working at all. You aren't passing it a function as the first argument.
You are calling alert immediately and trying to use it's return value as the function to repeat.
var timerID = setInterval(function () { alert(left_num1) }, 1000);
So you've got two different problems here:
// (1) timerID needs to be defined in a scope accessible to both hover callbacks
var timerID = null;
$("div.scroll_left").hover(function(){
var left_num = $('div.license_video').css("left")
var left_num1 = parseInt(left_num, 10) - 1;
// (2) Pass a *function* to setInterval
timerID = setInterval(function () {
alert(left_num1)
}, 1000);
}, function(){
clearInterval(timerID);
timerID = null;
});
When you write
setInterval(alert(left_num1), 1000);
// or
setInterval(slideleft(left_num1), 1000);
you are passing the value returned by calling alert() or slideleft() (respectively) to setInterval. You are not passing the function itself.
You are assigning null to be the function to call. Why? Because you called alert and assigned its return value to the setInterval parameter.
Instead, use an anonymous function:
setInterval(function() {doStuff();},1000);
Very easy ;-) ... i love jquery, no matter a version... u need javascript pure is send pm me is can help.
umavez = 0;
setInterval(function() {
if (umavez == 0) {
for (x=0;x<10;x++) {
$('div.test').append('<div>'+x+'</div>');
}
}
umavez = 1;
}, 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="test">Linha:</div>

Change millisec for window.setInterval function

I used window.setInterval function. this function includes 3 arguments :
setInterval(code,millisec,lang)
I used that like this:
var counter = 1;
window.setInterval(function() {}, 1000 * ++counter);
but when first time set timer (second argument), is not changed and that act Like below code:
window.setInterval(function() {}, 1000);
please write correct code for change timer
Use window.setTimeout instead.
var delay = 1000;
function myTimer() {
// do whatever
window.setTimeout(myTimer, delay);
}
window.setTimeout(myTimer, delay);
You can manipulate delay in the body of your function.
Your problem is that javascript first execute '1000 * ++counter' once and then do not update the time interval.
You should try to use a timeout instead: https://developer.mozilla.org/en/DOM/window.setTimeout
And create a new time out with the new value every time your time out function is called.
Sounds like what you're after is not setInterval but rather setTimeout in a loop:
var counter = 1;
for (var i = 1; i <= 3; i++) {
window.setTimeout(function() {
alert("#" + counter);
counter++;
}, i * 1000);
}
This will execute three different "timers" one after the other.
Live test case: http://jsfiddle.net/86DRd/

Categories

Resources