Reputation: 7392
I want to call myfun1 only once with setInterval. I want to avoid using a global variable. Read this but it does not work (just calls the function every 2000 ms). Naturally I need to call main() every 2000 ms.
(function($){
setinterval(main,2000);
function main (){
if(/*condition*/) return;
function callItOnce(fn) {
var called = false;
return function() {
if (!called) {
called = true;
return fn();
}
return;
}
}
myfun1 = callITOnce(myfun1);
myfun1();
function myfun1(){/*code*/};
function myfun2(){/*code*/};
function myfun3(){/*code*/};
})(jquery);
Upvotes: 0
Views: 1001
Reputation: 266
One easy way to work around this is to use a variable on the function itself.
function myFunc1(){
if(arguments.callee.done){return;}
arguments.callee.done = true;
}
This way the "done" variable on the method myFunc1 would make sure the method is executed only once.
Upvotes: 0
Reputation: 6329
The callItOnce
function you wrote should work. You just need to declare the function outside the setInterval
call. Otherwise it gets redefined each time.
(function () {
function myfun1(){/*code*/};
function myfun2(){/*code*/};
function myfun3(){/*code*/};
function callItOnce(fn) {
var called = false;
return function() {
if (!called) {
called = true;
return fn();
}
return;
}
}
myfun1 = callItOnce(myfun1);
function main() {
if(/*condition*/) return;
myfun1();
}
setInterval(main, 2000);
}());
Upvotes: 0
Reputation: 318252
Use a flag :
(function($){
var timer = setInterval(main,2000), ran=true;
function main() {
if(/*condition*/) return;
if (ran) { //runs when ran=true, which is only the first time
myfun1();
ran = false; //since it's set to false here
}
function myfun1(){/*code*/};
function myfun2(){/*code*/};
function myfun3(){/*code*/};
})(jquery);
Upvotes: 5
Reputation: 69944
setInterval returns a value that you can pass to clearInterval to stop the callback from being called.
var i = 0;
var timeout_id = setTimeout(function(){
console.log(i);
if(i >= 5){ clearTimeout(timeout_id) }
i++;
})
Upvotes: -1