最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do i timeout a jquery script thats set to run every second after half an hour? - Stack Overflow

programmeradmin1浏览0评论

I have a jQuery script that runs a function every second with setinterval. But i want to set a timeout for that so after half an hour it kills the script. How do i do this? Thanks :)

source code:

<script type="text/javascript" src="/
libs/jquery/1.3.0/jquery.min.js"></script>

<script type="text/javascript">
$(function() {
    setInterval(oneSecondFunction, 1000);
});

function oneSecondFunction() {
    //var ID = $(this).attr("id");
    var ID = '1';
    if(ID){
        $("#more"+ID).html('<img src="moreajax.gif" />');
        $.ajax({
            type: "POST",
            url: "ajax_more.php",
            data: "lastmsg="+ ID, 
            cache: false,
            success: function(html){
                $("ol#updates").prepend(html);
                $("#more"+ID).remove();
            }
        })
    }
    return false;
}
</script>
<style>

I have a jQuery script that runs a function every second with setinterval. But i want to set a timeout for that so after half an hour it kills the script. How do i do this? Thanks :)

source code:

<script type="text/javascript" src="http://ajax.googleapis./ajax/
libs/jquery/1.3.0/jquery.min.js"></script>

<script type="text/javascript">
$(function() {
    setInterval(oneSecondFunction, 1000);
});

function oneSecondFunction() {
    //var ID = $(this).attr("id");
    var ID = '1';
    if(ID){
        $("#more"+ID).html('<img src="moreajax.gif" />');
        $.ajax({
            type: "POST",
            url: "ajax_more.php",
            data: "lastmsg="+ ID, 
            cache: false,
            success: function(html){
                $("ol#updates").prepend(html);
                $("#more"+ID).remove();
            }
        })
    }
    return false;
}
</script>
<style>
Share Improve this question asked Apr 14, 2011 at 20:28 user663049user663049 1,1783 gold badges14 silver badges28 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 5

Use this pattern:

var timer = null;

$(function() {
    timer = setInterval(oneSecondFunction, 1000);
    setTimeout(function() { clearInterval(timer); }, 30*60*1000);
});

Save the timer it creates when you do setInvterval and clear the interval after 30 minutes.

I.E.

var t = setInterval(oneSecondFunction, 1000);
setTimeout(function() { clearInterval(t); }, 30*60*1000);

you can do this:

<script type="text/javascript">
$(function() {
    var interval= setInterval(oneSecondFunction, 1000);
    setTimeout(function(){clearInterval(interval)}, 18000000); //half an hour
});
...
</script>
<style>
发布评论

评论列表(0)

  1. 暂无评论