SetTimeout. Stop timer - javascript

As in this example to stop setTimout?
var i = 1;
var timerId = setTimeout(function tick() {
if (i == 5) clearTimeout(timerId);
i++;
console.log("Tick");
timerId = setTimeout(tick, 2000);
}, 2000);
I know this code you can change and then everything will work, but I wanted to understand why the first example does not work.
var i = 1;
var timerId = setTimeout(function tick() {
console.log('Tick');
if (i < 5) setTimeout(tick, 2000);
i++;
}, 2000);

The first code snippet continues looping because:
You are changing the timerId with every new timeout you set.
You are clearing the timeout that has already finished executing (because it has called the function), and then creating a new one.
You should be using setInterval() instead of setTimeout(), as an interval will keep repeating indefinitely at the specified frequency, whereas a timeout will only execute once after the specified time has elapsed.

The first example isn't working because you're always setting a timeout, no matter the value of i. Add a return statement if i is equal to 5
var i = 1;
var timerId = setTimeout(function tick() {
if (i == 5) {
return;
}
i++;
console.log("Tick");
timerId = setTimeout(tick, 2000);
}, 2000);

It's OK to clearTimeout after the timer expired, but it's not necessary.
and just because of that, your second code snippet is superior to the first one.
and in your first code snippet, you always set the timeout, even if your if condition is met, and you are suppose to return,
i will re-write the function as shown below
var i = 1;
function tick() {
if (i == 5) {
return;
}
i++;
console.log("Tick");
setTimeout(tick, 2000);
}
setTimeout(tick, 2000);
or using interval as
var i = 1;
function tick() {
if (i == 5) {
clearInterval(timerId);
return;
}
i++;
console.log("Tick");
}
var timerId = setInterval(tick, 2000);

Related

How to make a setTimeout to call a setInterval to make it execute after some time?

I want my doSomething to be executed after some amount of time different than the interval of the setInterval, so I used setTimeout(doSomething, 5000); so I could call doSomething after say 5 seconds, but that doesn't seem to happen.
Regarding that I need to use clearInterval for the setInterval to stop executing in the condition I declared, and I need to have an interval time for the setInterval to be different from the delay of doSomething execution start, how can I make doSomething to start executing after 5 seconds?
function doSomething() {
let a = 1;
return setInterval(() => {
console.log(a);
if (a < 6) {
a++;
} else {
return a = 1;
clearInterval(id);
}
}, 1000);
}
var id = doSomething();
setTimeout(doSomething, 5000);
var id = doSomething(); calls the function (and thus starts the interval) immediately.
Since both the setInterval() and clearInterval() are within the same function, there is no need to return the interval ID. Just keep track of it locally in the function. That way you only need to invoke doSomething() and it will start and stop by itself.
Lastly, note that setInterval()'s first invocation will not be immediately, but also wait for the given delay. So if you want the first invocation to be after 5 seconds, you will need to subtract the 1000 of the setInterval() from the 5000 of the setTimeout(). (Or alternatively invoke the repeated function manually immediately.)
function doSomething() {
let a = 1;
let intervalId = setInterval(() => {
console.log(a);
if (a < 6) {
a++;
} else {
clearInterval(intervalId);
}
}, 1000);
}
setTimeout(doSomething, 4000);
setTimeout run doSomething about 4s delay
and doSomething do the first console.log about 1s delay
so the first first console.log start after 4s + 1s == 5s delay
function doSomething() {
let a = 1
, id = setInterval(() => {
console.log(a++);
if (a > 5) clearInterval(id);
}, 1000);
}
setTimeout( doSomething, 4000);
First of all. If you call the function that creates an interval, it will create an interval. You cannot call the function and expect it to have a timeout if you dont use a timeout.
This works:
function foo() {
var i = 0;
var iId = setInterval(() => {
console.log('Hello World -' + i);
i++;
if (i > 5) {
clearInterval(iId);
}
}, 1000);
}
then:
setTimeout(() => { foo(); }, 5000)
try doing it like this
function doSomething() {
let a = 1;
return setInterval(() => {
console.log(a);
if (a < 6) {
a++;
} else {
clearInterval(id)
return a = 1;
}
}, 1000);
}
var id = doSomething();
setTimeout(doSomething, 5000);

Why the timer setTimeout returns the first value "2"

below the code. It should write down to console numbers from 0 to 19. Actually it does. But what is the first number it has print in console?
var i = 0;
var timerId = setInterval(function () {
console.log(i++);
}, 100);
setTimeout(function() {
clearTimeout(timerId)
}, 2100);
Although your code works as expected, it could be that under some conditions you wouldn't print all numbers. It might be better to check the counter value and then clear the interval at that time (timing in javascript is not really that precise as you might hope it to be)
You could try to do it like this though, to make sure that your interval can only run once, and that you don't exceed your max value.
function Counter(start, maxValue, ticks) {
this.value = start || 0;
this.max = maxValue;
this.ticks = ticks;
var interval;
this.stop = function() {
if (!interval) {
return;
}
clearInterval(interval);
console.log('stopped counter');
};
this.increase = function() {
this.value++;
console.log(this.value);
if (this.value >= this.max) {
this.stop();
}
};
this.start = function() {
if (interval) {
return;
}
console.log('starting counter');
interval = setInterval(this.increase.bind(this), this.ticks || 0);
};
}
var counter = new Counter(0, 20, 100);
counter.start();
From setInterval documentation
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function. Returns an intervalID.

How to run a javascript function X seconds?

I am using setInterval to run a Javascript function that generates a new, random integer in a div. the timer starts when I click on the div. I am having problems with stopping it form generating new numbers after five seconds.
Using setTimeout, I hide the div after 5 seconds; that stops random numbers, but I lose the div.
How can I efficiently stop the generating of numbers in the div, and not hide it?
HTML:
<div id="div" onmousedown='F();'>Click here</div>
JS:
function F(){
var div = document.getElementById("div");
setInterval(function(){
var number = Math.floor(Math.random()*28) ;
div.innerHTML = number;
}, 1000);
setTimeout(function(){
div.style.display = 'none';
},5000);
};
Just use a counter to keep track of the number of times the interval has ticked and then use clearInterval to stop it:
var count = 0;
var intervalID = setInterval(function() {
// generate your random number
count++;
if (count === 5) {
clearInterval(intervalID);
}
}, 1000);
Something hastily written, but what you want to do is keep track of your interval handle and then clear it. You can do this with a setTimeout
var forXsecs = function(period, func) {
var handle = setInterval(func, 1000);
setTimeout(function() { clearInterval(handle); }, period * 1000);
}
The timing is not perfect. Matt's answer would also work.
Another option is a slight change on Matt's answer that removes setInterval and just uses timeouts.
var count = 0;
var forXsecs = function(period, func) {
if(count < period) {
func();
count++;
setTimeout(function() {forXsecs(period, func);}, 1000);
} else {
count = 0; //need to reset the count for possible future calls
}
}
If you just want to simply let it run once each second and that 5 times you can do it like this:
HTML:
<div id="5seconds"></div>
JS:
var count= 0;
setInterval(function(){
if(count < 5){
document.getElementById('5seconds').innerHTML = Math.random();
count++
}
},1000);
This will generate a random number each second. until 5 seconds have passed
you should use clearInterval to stop the timer.
To do so, you pass in the id(or handle) of a timer returned from the setInterval function (which creates it).
I recommend clearing the interval timer (using clearInterval) from within the function being executed.
var elm = document.querySelector("div.container");
var cnt = 0;
var timerID;
function generateNumber()
{
cnt += 1;
elm.innerText = cnt;
if (cnt >= 5) {
window.clearInterval(timerID);
}
}
timerID = window.setInterval(generateNumber, 1000);
.container {display:block; min-width:5em;line-height:5em;min-height:5em;background-color:whitesmoke;border:0.1em outset whitesmoke;}
<label>1s Interval over 5s</label>
<div class="container"></div>

jQuery - End setInterval Loop

I'm running the following.
setInterval(function()
{
update(url, baseName(data));
}
, 1000);
This calls that update function every second.
Is there a way to keep this functionality of calling update every second, but killing it or ending it after 10 seconds?
Have a counter and store the interval reference, then use clearInterval() to end the calls
var counter = 0;
var timer = setInterval(function () {
counter++;
update(url, baseName(data));
if(counter>=10){
clearInterval(timer)
}
}, 1000);
Keep a counter:
var timesCalled = 0;
var t = setInterval(function() {
update(url, baseName(data));
timesCalled++;
if (timesCalled === 10)
clearInterval(t);
}, 1000);
(clearInterval)

setTimeout counter not working

This setTimeout function only runs once and then stops. I get no errors so I have no idea why it's happening.
count = 100;
counter = setTimeout('timer()', 100);
$('#reset').click(function() {
count = 100;
counter = setTimeout('timer()', 100);
})
function timer() {
if (count <= 0) {
clearTimeout(counter);
alert('done');
}
$('#counter').html(count);
count -= 1;
}
I tried a few different formulations of the setTimeout function, including setTimeout(timer(),100) and setTimeout(function() { timer() }, 100)
You should be using setInterval() which repeats a function call, not setTimeout(), which does it once. Also, don't use () in function name reference.
var count = 100;
var counter = setInterval('timer', 100);
$('#reset').click(function() {
count = 100;
counter = setInterval('timer', 100);
})
function timer() {
if (count <= 0) {
clearInterval(counter);
alert('done');
}
$('#counter').html(count);
count -= 1;
}
Yes, that's what setTimeout does. It runs the code once.
You want to use the setInterval method to run the code repeatedly.
setTimeout works correctly but it is not what you are looking for. try setInterval instead. setInteval(function, delay)
setTimeout() - executes a function, once, after waiting a specified number of milliseconds.
You probably would like to go for setInterval() which executes a function, over and over again, at specified time intervals.
Not sure what you're trying to achieve, and I don't understand the $('#reset').click (etc) constructs. Are these JQuery?
However, why not use setInterval()? And then clear the interval timer when your condition is met?
var count = 10;
function counter() {
if ( count > 0 )
{
--count;
var t2 = setTimeout( counter, 1000 );
document.querySelector("#demo").innerHTML = count;
}
else
{
clearTimeout(t2);
document.querySelector("#demo").innerHTML = "Done";
}
}
var countdown_timeout = counter();
<p>Count: <b><span id="demo"></span></b></p>

Categories