-1

I have been trying to fix this script for more than an hour and still can't get it to work. It is a loop performing animate and html jquery events in a setInterval.

Here is the fiddle: http://jsfiddle.net/GNrL3/

Here is the code (same as fiddle but some prefer to have it here):

$(document).ready(function() {

var i = 1;
var startinterval = 0;

$('#clickhere').click(function() {
    startinterval = setInterval("curvalues()", 1000);
});

function curvalues() {
    if ($i == 20) {
        clearInterval(startinterval);
    }
    else {
        $("#square").animate({
            "left": "+=30px"
        }, "slow");
        $("#text").html("Barracks");
        $i++;
    }
}

});

<div id="square" style="position:absolute;height:30px;width:30px;background-color:#F07014;"></div>
<br /><br /><br /><br /><br />
<div id="text" style="height:30px;width:100px;border:1px solid #000">Text box</div>
<br /><br />
<input type="button" value="Start" id="clickhere"/>

My belief is that the issue concerns the setInterval of the function, but still, the syntax seems good to me...

2 Answers 2

3

You have a function-scope problem. Instead of this:

setInterval("curvalues()", 1000);

do this:

setInterval(curvalues, 1000);

EDIT You have one more mistake. Your counter variable has a wrong name. It should be declared like this:

var $i = 1; //You missed the '$'

(or reference all your vars with i instead of $i)

I updated your fiddle: http://jsfiddle.net/GNrL3/1/ and it works now.

Hope this helps. Cheers

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I keep learning everyday! While you're there, do you have any idea if there is a way to pause/resume the function or this is impossible to do?
@Edgar I know, but I just want to pause it and start it back again where it was paused (not from the beginning)
2

Change this line:

startinterval = setInterval("curvalues()", 1000);

To this:

startinterval = setInterval(curvalues, 1000);

Or this:

startinterval = setInterval(function() { curvalues(); callSomethingElse(); }, 1000);

And get rid of the $ in front of i. There's no need for that.

4 Comments

Btw, do you have any idea if there is a way to pause/resume the function or this is impossible to do?
To stop what setInterval started call clearInterval(startinterval);. Though I think "startinterval" is a bad name for a variable in this case and I'd change it to something like "timer" or just "interval".
I know, but I just want to pause it and start it back again where it was paused (not from the beginning)
Then make sure your logic within the function being invoked by setInterval doesn't reset variables upon execution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.