2013-08-29 22 views
1

我需要能够在运行时停止setInterval函数。 的想法是,如果浏览器被调整,然后将定时器(320像素或更低) 这里是间隔:stop setInterval while its running javascript

var blurb_scroll = setInterval(function(){ 
     $(".content .blurb-container:first").next().css({'opacity':0}).delay(400).animate({'opacity':1}, 'fast'); 
     $(".content .blurb-container:first").animate({'margin-top':'-190px', 'opacity':'0'}, 'slow', function(){ 
      $(this).appendTo(blurb_container).removeAttr('style'); 
     }); 
    },6000); 
+6

'clearInterval(blurb_scroll)' – Cherniv

+0

它不工作,这就是为什么我感到沮丧,并来到这里问。 – cppit

+1

@fogsy:为什么它不起作用?发生了什么?你在哪里叫它? – SLaks

回答

1

必须我们可以使用clearInterval。把你的setInterval作为全局变量,然后你可以在任何地方停下来。

<html> 
<body> 

<input type="text" id="clock"> 
<script language=javascript> 
var int=self.setInterval(function(){clock()},1000); 
function clock() { 
    var d=new Date(); 
    var t=d.toLocaleTimeString(); 
    document.getElementById("clock").value=t; 
    } 
</script> 
</form> 
<button onclick="int=window.clearInterval(int)">Stop</button> 

</body> 
</html> 

Here你可以在这个例子中找到更多有关clearInterval的信息。

希望它能帮助!

1

要停止间隔以及动画,您需要使用clearInterval(间隔ID)和.stop()(在元素上)。

例如:

clearInterval(blurb_scroll); 
$(".content .blurb-container:first").stop(); 
1

您应按照jQuery文档http://api.jquery.com/stop/

另外,作为jQuery的状态我们可以使用clearInterval和jQuery .stop()函数,动画可以在全球范围内通过设置属性$停止。 fx.off为true。完成此操作后,所有动画方法将在调用时立即将元素设置为其最终状态,而不是显示效果。

0

而不是清除了setInterval的时间间隔,开始使用的setTimeout来代替:

(function runthis() { 
    var f = $(".content .blurb-container:first") 
    f.next() 
    .css({'opacity':0}) 
    .delay(400) 
    .animate({'opacity':1}, 'fast') 
    .animate({'margin-top':'-190px', 'opacity':'0'}, 'slow', function(){ 
    $(this).appendTo(blurb_container).removeAttr('style'); 
    }); 
    if (conditional that says we should keep doing this) { 
    setTimeout(runthis, 6000); 
    } 
}()); 

现在你有过发生什么更精细的控制,如果你的代码中有一个错误,至少它不会让你跑错误代码永远。如果它在发生错误时死亡,则永远不会安排新的超时。

setInterval。只是不是一个好主意。