开发者

jQuery setInterval isn't working

Here is my code:

$(document).ready(function() {
    var interval = setInterval("change_height()", 500);
    var height;

    function change_height() {
        height = parseInt(window.location.hash);
        $('#message_body').height(height);
        alert("");
        clearInterval(interval);
    }
});

for some reason the change_height() function just isn't being called yet it works if I put it outside the document.re开发者_JS百科ady block but then the clearInterval doesn't work!

Any help much appreciated.

Thanks


setInterval is a native javascript function and not a jQuery function.

With that cleared up, try just referencing the function directly using:

var interval = setInterval(change_height, 500);
    // Note the lack of () which would execute the function

This is better than letting the setInterval function interpret the string.


$(document).ready(function() {
    var interval = setInterval(function() { change_height(); }, 500);
    var height;

    function change_height() {
        height = parseInt(window.location.hash);
        $('#message_body').height(height);
        alert("");
        clearInterval(interval);
    }
});


Dont pass strings to setInterval, pass the function reference:

$(document).ready(function() {
    var interval;
    var height;

    function change_height() {
        height = parseInt(window.location.hash);
        $('#message_body').height(height);
        alert("");
        clearInterval(interval);
    }
    interval = setInterval(change_height, 500);

});


try this code sample:

var intervalId;

$(document).ready(function () {
    intervalId = window.setInterval('sample.func1();', 500);
});

var sample = {
    func1: function () {
        alert('test 1');
        window.clearInterval(intervalId);
    }
}


You have 2 choices:

1) Remove the parenthesis and quotes from setInterval:

setInterval(change_height, 500);

OR 2) Declare your function as global:

window.change_height = function() {
    height = parseInt(window.location.hash);
    $('#message_body').height(height);
    alert("");
    clearInterval(interval);
}

This is because when you were using "change_height()", setInterval was looking a global function, but your function was local.

Hope this helps. Cheers


Use settimeout. Because setinterval executes regardless of the code is finished. And call the settimeout from the last line in your function.

setTimeOut("change_height", 500); 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜