Timed for loop in Javascript - javascript

I don't even know how to get started with this: I need a for loop that executes a function (say a simple console.log()) with a timed delay between each execution. I've been trying to do it with setTimeout() and it never works. If I call the function that has the loop from setTimeout, it won't work. Ideally I'd want my for loop to print something x times, with a couple of seconds delay between each printing. Any ideas how that might work? I've tried something like this:
function printStuff(){
for(var i=0;i<5;i++){
console.log(i);
}
};
setTimeout(printStuff(),1000);

For me you should execute setInterval and inside this you should increase counter. When counter reach the limit you simply clear interval.
var counter = 0;
var limit = 10;
var myVar = setInterval(function(){
if (counter > limit)
{
clearInterval(myVar);
}
counter++;
console.log("test");
}, 1000);

init();
function init() {
setTimeout(init, 2*1000); // wait 2 sec then call init again
console.log(Date());
}
Or use setInterval:
// Call init after 2 sec and repeat calling it every 2. sec
setInterval(init, 2*1000);
function init() {
console.log(Date());
}

You could use the async module.
var count = 0;
async.whilst(
function () { return count < 5; },
function (callback) {
count++;
console.log(count);
setTimeout(callback, 1000);
},
function (err) {
// 5 seconds have passed
}
);
This way the count will be printed every second

var i = 0;
function timeout(){
setTimeout(log, 1000);
}
function log(){
console.log(i++);
timeout();
}
log();
http://jsfiddle.net/sq4v0kbf/

Use setInterval() instead of setTimeout(). Parameters are just the same:
setInterval(function () {
// your utility code goes here
}, 2000);

Here is one more way to do it. Use a wrapper function.
var time = 2000;
for (var i = 0; i < 10; i++) {
(function (i) {
setTimeout(function () {
console.log(i);
}, time);
})(i);
time+=2000;
}

You can create a sort of delayed loop function with the number of iterations/times you want to run. Something like this:
var delayedLoop = function (n, milliseconds) {
var iteration = function (n) {
if (n > 0) {
n--;
console.log(n);
setTimeout(function () {
iteration(n)
}, milliseconds);
}
};
iteration(n);
}
delayedLoop(4, 1000);
You could even expand the idea and even passing a function to be executed each time.
See demo.

Here's what I think is simpler (and doesn't have the fallbacks of) than a setInterval
var limit = 10,
counter = 0,
delay = 1000;
function doIt() {
document.body.innerHTML += 'Hit counter: ' + (counter++) + '<br />';
if (counter < limit) {
setTimeout(doIt, delay);
}
}
doIt();
And you can generalize it
function runTimedLoop(delay, howMany, callback) {
var index = 0;
function iteration() {
callback(index++);
if (index < howMany) {
setTimeout(iteration, delay);
}
}
iteration();
}
runTimedLoop(1000, 10, function(index) {
document.body.innerHTML += 'Hit counter: ' + (index++) + '<br />';
});

Related

clearInterval and set it again after x seconds

I want to do simple interval with with if, It is checking a variable's value and doing a function again().
again function contains clearInterval, i++ and setTimeout to call interval again after x seconds
var speed = 1000;
var wait = 0;
var i = 0;
function init() {
setInterval(function() {
if (i >= 6) i = 0;
if (i == 4) {
wait = 5000;
again(wait);
} else {
document.body.innerHTML = i;
i++;
}
}, speed);
}
function again(time) {
clearInterval(init());
i++;
setTimeout(function() {
setInterval(init(), speed);
}, time);
}
init();
I expect output like this:
1, 2, 3, Waiting x sec's , 5, 1, 2, ...
but code is doing some thing crazy, Its going faster and faster. I don't know why.
Here's a codepen with example (can crash your browser!)
Can you fix it and explain? Thanks
You are not clearing interval but use function inside clearInterval method. Method init which is used has no return statement so clearInterval gets undefined in attribute, so it is not clearing nothing.
Fixed code:
var speed = 1000;
var wait = 0;
var i = 0;
var interval=null;
function init() {
interval = setInterval(function() {
if (i >= 6) i = 0;
if (i == 4) {
wait = 5000;
again(wait);
} else {
document.body.innerHTML = i;
i++;
}
}, speed);
}
function again(time) {
clearInterval(interval);
i++;
setTimeout(function() {
init()
}, time);
}
init();
Function setInterval returns interval id and function clearInterval in attribute should get id of interval which we want to stop, so I created interval variable to save id. I am using this variable in clearInterval.
This is a small example how changing the delay of a setInterval call.
(function iife() {
var timer = null,
counter = 0;
function task() {
counter += 1;
console.log(counter);
// condition: every four reps
if (counter % 4 === 0) {
console.log("changed speed to 4 seconds");
return start(4000);
}
// condition: every seven reps
if (counter % 7 === 0) {
console.log("changed speed to 2 seconds");
return start(2000);
}
}
function start(delay) {
clearInterval(timer);
console.log("runs every " + delay + " miliseconds");
timer = setInterval(task, delay);
}
start(1000);
}());

setInterval function returning undefined

I am learning setInterval in JavaScript for the first time, and am trying to show a value after 5 seconds. My code is given below:
<button onclick="myTest()">Try it</button>
<script>
function myTest() {
const ret = myFunction();
alert(ret);
}
function myFunction() {
let i = 0;
const interval = setInterval(function(){
i += 1;
if (i === 5) {
clearInterval(interval);
return i;
}
}, 1000);
}
</script>
I want 5 to be alerted, instead I am getting undefined. Does anyone know why this is happening? Thanks in advance!
You can't return anything from the anonymous function within the setInterval call. You need to write to the console from within that function. Try this:
function myTest() {
// this function is now redundant - you could call myFunction() directly
myFunction();
}
function myFunction() {
let i = 0;
const interval = setInterval(function() {
i += 1;
if (i === 5) {
clearInterval(interval);
console.log(i); // this will appear after 5 seconds...
}
}, 1000);
}
myTest();
return i;
i will be returned to Window (I guess), not to myFunction.
myFunction return undefined by default as you did not write a return .
function myTest() {
myFunction(function(val){
alert(val);
});
}
function myFunction(callback) {
let i = 0;
const interval = setInterval(function(){
i += 1;
if (i === 5) {
clearInterval(interval);
if(callback){
callback(i);
}
}
}, 1000);
}
you can get your value in a callback function .
The alert(ret) will occur before 5 seconds are over and thus my function will return undefined. Try this way.
<button onclick="myTest()">Try it</button>
<script>
function myTest() {
myFunction();
}
function myFunction() {
var i = 0;
var interval = setInterval(function(){
i++;
if (i === 5) {
alert(i);
clearInterval(interval);
}
}, 1000);
}
</script>

Changer SetInterval Values After Interval

If I can try to make everyone understand what I am looking for, I am looking for the value of the interval to change to lets say "5000ms" after "1000ms" and then it would go on to the next value such as "2000ms" and repeat all over again! The current code I have is pretty much a stopwatch, It adds the number 1 to a paragraph every 1000ms. Any help is extremely appreciated!
<script>
function myFunction() {
clicks += 1;
}
setInterval(myFunction, 1000);
var clicks = 0;
function myFunction() {
clicks += 1;
document.getElementById("demo").innerHTML = clicks;
// connects to paragraph id
}
</script>
<p id="demo"></p>
<!--connects to getElementById-->
Don't use setInterval - this functions will perform the action in any given interval, which you set once.
Use setTimeout instead. Which performs the action only once after given interval, and then call it again and again with different interval values.
what about this
<script>
var clicks = 0;
myFunction(1000);
function myFunction( currentInterval ) {
clicks ++;
document.getElementById("demo").innerHTML = clicks;
if ( currentInterval == 1000 )
{
currentInterval = 5000;
}
else if ( currentInterval == 5000 )
{
currentInterval = 2000;
}
else
{
currentInterval = 1000;
}
setTimeout( function(){ myFunction( currentInterval ) }, currentInterval );
}
</script>
<p id="demo"></p>
you should try using recursive timeout instead of interval
var timeout = 1000;
var timer;
function startTimer() {
clearTimeout(timer);
timer = setTimeout(function() {
console.log('tick');
startTimer();
}, timeout);
}
startTimer();
// timeout = 2000
// timeout = 500
// clearTimeout(timer); to cancel
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
This might look a little complicated but you can try something like this:
JSFiddle.
(function() {
var interval = null;
var limit = 5;
function initInterval(callback, index) {
var msToSec = 1000;
if (interval) {
clearInterval();
}
console.log("Delay: ", index)
interval = setInterval(callback, index * msToSec);
}
function clearInterval() {
window.clearInterval(interval);
interval = null;
}
function resetInterval(callback, count) {
clearInterval();
initInterval(callback, count);
}
function main() {
var count = 1;
var notify = function() {
console.log("Hello World: ", count);
var _nextCount = ((count++) % limit) + 1;
if (count < 10) {
resetInterval(notify, _nextCount);
} else {
console.log("Stoping loop...");
clearInterval();
}
}
initInterval(notify, count);
}
main()
})()

countdown timer stops at zero i want it to reset

I am trying to figure out a way to make my countdown timer restart at 25 all over again when it reaches 0. I dont know what I am getting wrong but it wont work.
Javascript
window.onload = function() {
startCountDown(25, 1000, myFunction);
}
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
//write out count
countDownObj.innerHTML = i;
if (i == 0) {
//execute function
fn();
//stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
);
}
//set it going
countDownObj.count(i);
}
function myFunction(){};
</script>
HTML
<div id="countDown"></div>
try this, timer restarts after 0
http://jsfiddle.net/GdkAH/1/
Full code:
window.onload = function() {
startCountDown(25, 1000, myFunction);
}
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
startCountDown(25, 1000, myFunction);
// stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
}, pause);
}
// set it going
countDownObj.count(i);
}
function myFunction(){};
​
I don't see you resetting the counter. When your counter goes down to 0, it executes the function and return. Instead, you want to execute the function -> reset the counter -> return
You can do this by simply adding i = 25 under fn() :
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
i = 25;
// stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
);
}
// set it going
in #Muthu Kumaran code is not showing zero after countdown 1 . you can update to this:
if (i < 0) {
// execute function
fn();
startCountDown(10, 1000, myFunction);
// stop
return;
}
The main reason for using setInterval for a timer that runs continuously is to adjust the interval so that it updates as closely as possible to increments of the system clock, usually 1 second but maybe longer. In this case, that doesn't seem to be necessary, so just use setInterval.
Below is a function that doesn't add non–standard properties to the element, it could be called using a function expression from window.onload, so avoid global variables altogether (not that there is much point in that, but some like to minimise them).
var runTimer = (function() {
var element, count = 0;
return function(i, p, f) {
element = document.getElementById('countDown');
setInterval(function() {
element.innerHTML = i - (count % i);
if (count && !(count % i)) {
f();
}
count++;
}, p);
}
}());
function foo() {
console.log('foo');
}
window.onload = function() {
runTimer(25, 1000, foo);
}

Run a function a specified number of times

function runAgain()
{
window.setTimeout(foo, 100);
}
function foo()
{
//Do somthing
runAgain();
}
I can use the above code to run a function infinite number of times with an interval of one second.
What is the standard way of running a function defined number of times. Lets say, I want foo() to be run 5 times with an interval of 1 second.
EDIT It's said that global variables should be avoided in Javascript. Isn't there a better way?
With input from answers, I created a function like this: (Working Example: http://jsbin.com/upasem/edit#javascript,html )
var foo = function() {
console.log(new Date().getTime());
};
var handler = function(count) {
var caller = arguments.callee;
//Infinite
if (count == -1) {
window.setTimeout(function() {
foo();
caller(count);
}, 1000);
}
if (count > 0) {
if (count == 0) return;
foo();
window.setTimeout(function() {
caller(count - 1);
}, 100);
}
if (count == null) {foo(); }
};
handler(-1); //Runs infinite number of times
handler(0); //Does nothing
handler(2); //Runs two times
handler(); //Runs foo() one time
var counter = 1;
function foo()
{
if (counter < 5){
counter++
window.setTimeout(foo, 1000);
}
}
foo()// it will run 5 times;
LIVE DEMO
Version with "static variable":
function foo() {
if (typeof foo.counter == 'undefined') {
foo.counter = 0;
}
alert("Run No. " + (++foo.counter));
if (foo.counter < 5) {
setTimeout(function() {
foo(foo.counter + 1);
}, 400);
}
}
foo();
LIVE DEMO
Version with hidden input
function foo() {
var counter = document.getElementById('counter');
var counterValue = parseInt(counter.value, 10);
alert('Run No. ' + counterValue);
if (counterValue< 5) {
counter.value = counterValue + 1;
window.setTimeout(foo, 400);
}
}
foo();​
LIVE DEMO
Version with closure :
var x = function() {
var counter = 1;
(function foo() {
alert('Run No. ' + counter);
if (counter < 5) {
counter++;
setTimeout(foo, 400);
}
})();
};
x();​
LIVE DEMO
Assuming you have a function:
var foo = function() {
...
};
or if you prefer:
function foo() {
...
}
you could invoke it 5 times at intervals of 1 second like that:
(function(count) {
if (count < 5) {
// call the function.
foo();
// The currently executing function which is an anonymous function.
var caller = arguments.callee;
window.setTimeout(function() {
// the caller and the count variables are
// captured in a closure as they are defined
// in the outside scope.
caller(count + 1);
}, 1000);
}
})(0);
And here's a live demo.
use a global variable and increment it in the function foo() to count the number of times it has been called.
var counter=0;
function runAgain()
{
window.setTimeout(foo, 1000);
}
function foo()
{
//Do somthing
if((++counter)<5)
runAgain();
}
To avoid polluting the global environment with additional variables, you can wrap it in an anonymous function:
(function() {
var counter = 0;
function foo() {
// do stuff
if ((++counter) < 5) window.setTimeout(foo, 1000);
}
})();
function call (func, arg) {
return {
func,
arg,
times: function (num) {
let counter = 0;
while (counter < num) {
this.func(this.arg);
counter += 1;
}
}
};
}
Then to use it, you can do
call(yourFunction).times(10)
or, if you need to enter an argument:
call(yourFunction, arg).times(10)

Categories

Resources