开发者

setInterval issue (js)

开发者 https://www.devze.com 2023-03-18 02:00 出处:网络
I have been trying to fix this script for more than an hour开发者_StackOverflow社区 and still can\'t get it to work. It is a loop performing animate and html jquery events in a setInterval.

I have been trying to fix this script for more than an hour开发者_StackOverflow社区 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...


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消