setTimeout counter not working - javascript

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>

Related

How to print number after a delay in JS

It's beginner's question. I'm trying to understand setTimeout. I want to print each number after a delay of 2 seconds. However, I can only delay the whole function, not the numbers. Can anyone tell me how to do it?
function print() {
for (let i = 10; i >= 0; i--) {
console.log(i);
}
}
setTimeout(print, 2000);
You need to use the setTimeout inside the print method (inside the for), and give a different delay for each iteration.
function print() {
for (let i = 10; i >= 1; i--) {
setTimeout(() => {
console.log(i);
}, 2000 * (10 - i));
}
}
print();
Another approach is using setInterval. It is more natural for this task then setTImeout.
let i = 10;
const interval = setInterval(() => {
console.log(i);
i--;
if(i === 0){
clearInterval(interval);
}
}, 2000);
setTimeout here will delay all the function and if I get what you want to do is to print each number in 2s delay.
ill recommend using Promises and async function.
here is a solution with only setTimeout
function print(i){
console.log(i)
if(i>0){
setTimeout(()=>{print(i-1)},2000)
}
}
print(10)
Another way to do this by setInterval
let limit = 10
console.log('start')
let interval = setInterval(()=>{
console.log(limit--)
if(!limit){
clearInterval(interval)
console.log('end')
}
},2000)
With immediate start from 10 without 2 seconds wait.
let limit = 10
console.log('start')
const executeLogic = () =>{
console.log(limit--)
}
executeLogic()
let interval = setInterval(()=>{
executeLogic()
if(!limit){
clearInterval(interval)
console.log('end')
}
},2000)

How do I loop this function?

I am using Odometer to show an animated counter:
setTimeout(function (){
$('.odometer').html(8567);
}, 1000);
</script>
<script>
window.odometerOptions = {
duration: 3000
};
I would like the counter to start over at the value I've defined in my html (which is 1000) and then count back up to 8567 and repeat indefinitely. I've tried:
$(document).ready(function () {
function loop(){
setTimeout(function (){
$('.odometer').html(8567);},1000,loop);
loop();
});
But it breaks the counter. I'm assuming I can't mix the setTimeout while defining the loop, but don't know what else to try. The 1000 in the setTimeout function is just a coincidence and is the delay to start the function after page load.
If you want to repeatedly call a function over time like this you should use setInterval not setTimeout.
You need to keep track of the current value of the loop, yours right now is setting the counter to 8567 every time.
const start = 1000;
const max = 1010;
var c = start;
var el = document.getElementById('counter');
function counter() {
if (c > max) {
c = start;
}
el.innerHTML = c + "";
c++;
}
counter(); // Optional, can exclude if you want to delay starting the timer
setInterval(counter , 1000)
<div id="counter"></div>

Set timer for loop in javascript

I want to set timer-based for loop in JavaScript.
for (var i = 0; i < 20; i++) {
console.log(i)
}
How I can I repeat this loop every second and show the value of i (the counter)?
if you want to control your loops wait time you can combine settimeout with recursion
var i = 0;
function callMe() {
var timetowait = 100;
// some condition and more login
i++;
if(i < 20) {
setTimeout(callMe, timetowait);
}
}
callMe();
I think this is what you are looking for:
var counter = 0;
setInterval( function(){
console.log(counter);
counter++;
},1000);
You can try this approach too:
function loop(start, end, delay, fn) {
if (start > end) return;
function step(){
// callback fn with current iteration and
// recursively calls loop
fn(start);
loop(start + 1, end, delay, fn);
}
setTimeout(step, delay);
}
usage :
loop(1, 20, 1000, console.log)
var i = 0;
function myFunc() {
console.log(i);
i++;
if(i == 20) {
clearInterval(interval);
}
}
var interval = setInterval(myFunc, 1000);
The setInterval() method calls a function or evaluates an expression at -
specified intervals (in milliseconds).
The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.

SetTimeout. Stop timer

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

Want a javascript function to run every minute, but max 3 times

I have a ajax javascript method that pulls data from a page etc.
I want this process to run on a timed interval, say every minute.
But I don't want it to loop forever, so max out at 3 times.
What is the best way to implement this?
Like this:
var runCount = 0;
function timerMethod() {
runCount++;
if(runCount > 3) clearInterval(timerId);
//...
}
var timerId = setInterval(timerMethod, 60000); //60,000 milliseconds
A closure-based solution, using setInterval() and clearInterval():
// define a generic repeater
var repeater = function(func, times, interval) {
var ID = window.setInterval( function(times) {
return function() {
if (--times <= 0) window.clearInterval(ID);
func();
}
}(times), interval);
};
// call the repeater with a function as the argument
repeater(function() {
alert("stuff happens!");
}, 3, 60000);
EDIT: Another way of expressing the same, using setTimeout() instead:
var repeater = function(func, times, interval) {
window.setTimeout( function(times) {
return function() {
if (--times > 0) window.setTimeout(arguments.callee, interval);
func();
}
}(times), interval);
};
repeater(function() {
alert("stuff happens!");
}, 3, 2000);
Maybe the latter is a bit easier to understand.
In the setTimeout() version you can ensure that the next iteration happens only after the previous one has finished running. You'd simply move the func() line above the setTimeout() line.
A reusable approach
function setMaxExeuctionInterval( callback, delay, maxExecutions )
{
var intervalCallback = function()
{
var self = intervalCallback;
if ( 'undefined' == typeof self.executedIntervals )
{
self.executedIntervals = 1;
}
if ( self.executedIntervals == maxExecutions )
{
clearInterval( self.interval )
}
self.executedIntervals += 1;
callback();
};
intervalCallback.interval = setInterval( intervalCallback, delay );
}
// console.log requires Firebug
setMaxExeuctionInterval( function(){ console.log( 'hi' );}, 700, 3 );
setMaxExeuctionInterval( function(){ console.log( 'bye' );}, 200, 8 );
This anonymous function (it doesn't introduce any new globals) will do what you need. All you have to do is replace yourFunction with your function.
(function(fn, interval, maxIterations) {
var iterations = 0,
id = setInterval(function() {
if (++iterations > maxIterations)
return clearInterval(id);
fn();
}, interval);
})(yourFunction, 60000, 3);
you can do with setInterval
var count = 0;
var interval = setInterval(yourFunction(), 1000);
function yourFunction (){
clearInterval(interval);
if(count < 3){
count ++;
interval = setInterval(yourFunction(), 1000);
}
// your code
}
To extend Tomalak function:
If you want to know how many cycles are left:
var repeater = function(func, times, interval) {
window.setTimeout( function(times) {
return function() {
if (--times > 0) window.setTimeout(arguments.callee, interval);
func(times);
}
}(times), interval);
}
and use:
repeater(function(left){
//... (do you stuff here) ...
if(left == 0) {
alert("I'm done");
}
}, 3, 60000);
Use setInterval, be sure to get a reference.
var X=setInterval(....);
Also, have a global counter
var c=0;
Inside the function called by the setIntervale do:
c++;
if(c>3) window.clearInterval(X);
You can use setInterval() and then inside the called function keep a count of how many times you've run the function and then clearInterval().
Or you can use setTimeout() and then inside the called function call setTimeout() again until you've done it 3 times.
var testTimeInt = 3;
function testTime(){
testTimeInt--;
if(testTimeInt>0)
setTimeOut("testTime()", 1000);
}
setTimeOut("testTime()", 1000);

Categories