This code keeps repeating, but i want it to happen twice, after the functions call and then after the set period of time using setTimeout
.
function alertit() {
alert('code');
setTimeout(alertit, 200);
}
alertit();
This code keeps repeating, but i want it to happen twice, after the functions call and then after the set period of time using setTimeout
.
function alertit() {
alert('code');
setTimeout(alertit, 200);
}
alertit();
Share
Improve this question
asked Jul 16, 2013 at 11:51
dzumla011dzumla011
6123 gold badges8 silver badges20 bronze badges
8 Answers
Reset to default 4function alertit(callAgain) {
alert('code');
if (callAgain) setTimeout("alertit(false)", 200);
}
alertit(true);
function alertit() {
alert('code');
}
alertit();
setTimeout(alertit, 200);
for example.
Could you try this
function alertit(){
// guard code
if ( alertit.times == 2 ) return ; // for 4 times, alertit.times == 4
alertit.times = alertit.times ? ++alertit.times: 1;
// your function logic goes here ..
alert( 'here function called ' + alertit.times );
setTimeout( alertit , 1000 );
}
alertit();
You can apply condition logic over here.
var callfunc = true;
function alertit() {
alert('code');
if(callfunc == true)
setTimeout(function(){ callfunc = false; alertit();}, 200);
}
alertit();
if the call to setTimeout
has to be inside:
function alertit() {
var f = function () {
alert('code');
}
f();
setTimeout(f, 200);
}
alertit();
If you are interested in a more general approach, you could set up something like this:
function callMultipleTimes(func, count, delay) {
var key = setInterval(function(){
if (--count <= 0) {
clearInterval(key);
}
func();
}, delay);
}
function alertit() {
alert('code');
}
callMultipleTimes(alertit, 2, 200);
FIDDLE
You can use two flags to achieve. count will make sure your method runs for two times and the execute flag makes sure only first time the timeout is set.
var execute = true;
var count = 0;
function alertit() {
if (count < 2) {
alert('code');
if (execute) {
setTimeout(alertit, 200);
execute = false;
}
}
}
alertit();
I see I have given a similar answer like tangelo which is doing the same in simple, easy steps.
Create a Global variable call It _Count = 0 and in the function alertit() do an if condition if ( _Count <> 1 ) call the function and then if this codition is true Increment your variable and call the function ...