/    Sign up×
Community /Pin to ProfileBookmark

setInterval not working within Function

I’m trying to invoke setInterval to animate some CSS styles for a predefined number of frames. But I can’t get my different browsers to run setInterval correctly:

[code]Function animate(numFrames,speed){
var frame=0;
var intID=window.setInterval(“internal()”,speed);
function internal(){
if(frame==numFrames){
window.clearInterval(intID);
}else{
alert(frame);
frame++;
}
}
}[/code]

For some reason the format

[code]setInterval(“internal()”,speed);[/code]

doesn’t seem to work.

I’ve tried the following permutation

[code]setInterval(internal,speed);[/code]

which works in Firefox and Safari. What’s going on?

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@UltimaterJan 31.2006 — You're approach is novel and the coding could use some cleaning. May I suggest re-writting everything from scratch.

Some random errors are that [color=blue]intID[/color] must be defined gloablly. The function [color=blue]internal[/color] must be defined globally. Use "function" instead of "Function". Just start over.


Try something along these lines (untested):
<i>
</i>function animate(numFrames,speed){
this.numFrames=numFrames;
this.speed=speed;
this.frame=0;
this.stop=function(){clearInterval(intID);}
this.interval=function(){if(this.frame==this.numFrames){this.stop();}else{alert(this.frame);this.frame++;}};
this.play=function(){if(window.intID)clearInterval(intID);intID=setInterval(this.interval,this.speed);}
}

Then execute it like so:
<i>
</i>var t=animate(3,1000);
t.play();
×

Success!

Help @MAB spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...