Run a function a specified number of times - javascript

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)

Related

NodeJS: Have a setInterval loop only while another variable is true

function setNormal() {
console.log(1)
}
function setAlert() {
console.log(2)
}
function alertFunction() {
alertVar = setInterval(alertFunc, 600);
}
function alertFunc() {
setAlert()
setTimeout(setNormal, 300)
}
alertFunction()
});
how do I make the function alertFunction() run only when (for example) var loop = 1 and then stop when var loop = 0?
(this is my first post to stackoverflow so sorry if I did this wrong)
use setTimeout with a condition.
var x = 1;
setTimeout(function foo(){
// this is a named function expression, foo name only exists inside itself
if(x!==0){
// do some code
console.log("Hello");
setTimeout(foo,1000);
}
},1000);
setTimeout(function(){
// change x after 3 seconds
x = 0;
},3000);
You can also use clear interval to do the same thing
var x = 1;
var interval = setInterval(function (){
if(x!==0){
// do some code
console.log("Hello");
}else{
clearInterval(interval)
}
},1000);
setTimeout(function(){
// change x after 3 seconds
x = 0;
},3000);
Use Like It:-
var alertVar;
function alertFunction() {
alertVar = setInterval(alertFunc, 600);
}
function myStopFunction() {
clearInterval(alertVar);
}
if(lool=1){
alertFunction();
}
if(lool=0){
myStopFunction();
}

I can't clear interval

I have a problem with the interval, which I can not clear after calling the function with a value.
The interval continues to increase the number and returns the percentage of the width.
Here my code:
function loadingClient(data) {
var loadingClientDiv = document.getElementById('loadingClient');
var percentageLoading = document.getElementsByClassName('percentageLoading');
var charge = 1;
var intervalLoadingClient = setInterval(barCharge, 1000);
function barCharge() {
if (charge >= 76) {
clearInterval(intervalLoadingClient);
} else {
++charge;
$(percentageLoading).css("width", charge + "%");
}
}
if (data === "100") {
clearInterval(intervalLoadingClient);
$(percentageLoading).css("width", "100%");
setTimeout(closeLoadingClient, 5000);
setTimeout(removeLoadingClient, 7000);
function closeLoadingClient() {
$(loadingClientDiv).hide("fade", 1000);
}
function removeLoadingClient() {
$(loadingClientDiv).remove();
}
}
}
loadingClient();
#hudolfhess is correct, you need to be using clearInterval instead of clearTimeout.
Also,
If you are trying to do something like this it wont work.
loadingClient() //Should start the interval.
loadingClient("100") //Should clear the interval, but doesn't.
you are trying to do? If so, you need to delcare intervalLoadingClient outside of the scope and avoid re-declaration of the variable when you call the method with parameters.
var intervalLoadingClient;
function loadingClient(data) {
var loadingClientDiv = document.getElementById('loadingClient');
var percentageLoading = document.getElementsByClassName('percentageLoading');
var charge = 1;
intervalLoadingClient = intervalLoadingClient || setInterval(barCharge, 1000);
function barCharge() {
if (charge >= 76) {
clearInterval(intervalLoadingClient);
} else {
++charge;
$(percentageLoading).css("width", charge + "%");
}
}
if (data === "100") {
clearInterval(intervalLoadingClient);
$(percentageLoading).css("width", "100%");
setTimeout(closeLoadingClient, 5000);
setTimeout(removeLoadingClient, 7000);
function closeLoadingClient() {
$(loadingClientDiv).hide("fade", 1000);
}
function removeLoadingClient() {
$(loadingClientDiv).remove();
}
}
}
loadingClient(); //Starts the interval
loadingClient("100"); //Ends the interval.

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>

Timed for loop in 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 />';
});

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

Categories

Resources