Javascript 如何清除间隔并重新设置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10935026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to clear interval and set it again?
提问by Dejo Dekic
This is what i am trying to accomplish: when the last slide is reached fadeOut last slide and then fadeIn first slide, and then clearInterval (everything works with this part). Now my problem is that i want to setInterval againif it doesn't exists but I don't know how to make it happen:(
I have tried to solve this with if statment but then my script doesn't work at all!
So how can I RESTART my interval again? THANK YOU!!
Withoutif statement like this it's working fine:
这就是我想要完成的事情:当最后一张幻灯片到达fadeOut 最后一张幻灯片然后fadeIn 第一张幻灯片,然后clearInterval (一切都适用于这部分)。现在我的问题是,如果setInterval不存在,我想再次设置它,但我不知道如何实现它:(
我试图用 if 语句解决这个问题,但我的脚本根本不起作用!
所以我怎样才能再次重新开始我的间隔?谢谢!!
没有这样的if 语句它工作正常:
if(!intervalID){
intervalID = setInterval(animate,5000);
}
This is what I have so far:
这是我到目前为止:
$(document).ready(function() {
/*check if intervalID don't exists messes UP!!*/
if (!intervalID) {
intervalID = setInterval(animate, 5000);
}
//Hide everything except first slide and controls
$('.slidewrap div:not(.slidewrap div:first,.slidewrap .slide_controls)').hide();
var animate = function() {
/*if .pagination_active is last removeClass and addClass to .pagination_active
first li tag*/
if ($('.pagination_active').is($('.slide_controls ul li:last'))) {
$('.pagination_active').removeClass('pagination_active');
$('.slide_controls ul li:first').addClass('pagination_active');
} else {
$('.pagination_active').removeClass('pagination_active').next().addClass('pagination_active');
}
/*if div.active is last fadeOut and add .active class
to the first div and fadeIn FIRST div then CLEAR INTERVAL and set intervalID to zero */
if ($('.active').is($('.slidewrap div:last'))) {
$('.active').fadeOut(1000).removeClass('active');
$('.slidewrap div:first').addClass('active').fadeIn(1000, function() {
clearInterval(intervalID);
intervalID = 0;
});
}
//OR .active fadeOut and next div fadeIn
else {
$('.active').fadeOut(1000).next().fadeIn(1000, function() {
$('.slidewrap div.active').removeClass('active').next('div').addClass('active');
});
}
}
var intervalID;
intervalID = setInterval(animate, 3000);
});
回答by thecodeparadox
After clear an interval you need to start it again with setInterval()
.
清除间隔后,您需要使用 再次启动它setInterval()
。
It would be better to make function for your setInterval()
最好为您的功能 setInterval()
var intervalID = null;
function intervalManager(flag, animate, time) {
if(flag)
intervalID = setInterval(animate, time);
else
clearInterval(intervalID);
}
Here flag
is a boolean
variable with value true/ false
. true
will execute setInterval()
and false
will clearInterval()
;
这flag
是一个boolean
带有 value的变量true/ false
。true
将执行setInterval()
和false
意志clearInterval()
;
Now you can use above function as you need.
现在您可以根据需要使用上述功能。
For example:
例如:
intervalManager(true, animate, 300); // for setInterval
intervalManager(false); // for clearInterval
回答by mcroteau
Here is utility object that takes a callback and interval which you can use to start and stop an interval.
这是带有回调和间隔的实用程序对象,您可以使用它们来启动和停止间隔。
//simple utility object to start and stop an interval
var IntervalUtil = function(functionCall, interval){
var intervalObj = 0,
INTERVAL = interval;
var callback = functionCall;
function startTimer(){
console.log('start timer', intervalObj)
if(intervalObj === 0){
intervalObj = setInterval(callback, INTERVAL)
}
}
function stopTimer(){
clearInterval(intervalObj);
intervalObj = 0;
console.log('timer stopped', intervalObj);
}
return {
startTimer : startTimer,
stopTimer : stopTimer
}
};
*You would use it like so *
*你会像这样使用它 *
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="author" content=""/>
<title>Timer : setInterval()</title>
<style type="text/css">
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
color:#000;
line-height:1.3em;
font: inherit;
vertical-align: middle;
font-family:arial;
font-size:12px;
outline:none;
}
a{
outline:none;
text-decoration:none;
color:#145486;
}
a span{
color:#145486;
}
h1{
font-weight:normal;
font-size:32px;
}
body{
background:#efefef;
text-align:center;
}
.content{
width:400px;
padding:20px;
margin:10px auto;
background:#fff;
border:solid 1px #ebebeb;
text-align:left;
}
#toggleTimer{
color:#fff;
font-size:10px;
padding:2px 7px;
display:inline-block;
background:#357cb7;
border:solid 1px #0c8af4;
}
#toggleTimer.running{
background:#f14621;
border:solid 1px #ff4c00;
}
#output{
padding:7px;
font-size:10px;
border:dashed 1px #ebebeb;
background:#f8f8f8;
margin-left:10px;
display:inline-block;
}
em{
font-weight:bold;
}
</style>
</head>
<body>
<div class="content">
<h1>Set Interval Code</h1>
<a href="javascript:" id="toggleTimer" class="">Start Timer</a>
<span id="output"></span>
<br class="clear"/>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var demo = new Demo();
});
var Demo = function(){
var self = this;
var START_TEXT = "Start Timer",
STOP_TEXT = "Stop Timer";
var $toggle = $('#toggleTimer'),
$output = $('#output');
var count = 0;
var intervalUtil;
function init(){
intervalUtil = new IntervalUtil(printMessage, 1000);
setClickHandler();
return self;
}
function setClickHandler(){
$toggle.click(toggleTimer)
}
function toggleTimer(){
$toggle.toggleClass('running');
if($toggle.hasClass('running')){
$toggle.text(STOP_TEXT);
intervalUtil.startTimer();
}else{
$toggle.text(START_TEXT);
intervalUtil.stopTimer();
}
}
function printMessage(){
$output.html("printMessage called <em>" + (count++) + "</em> times");
}
return init();
}
//simple utility object to start and stop an interval
var IntervalUtil = function(functionCall, interval){
var intervalObj = 0,
INTERVAL = interval;
var callback = functionCall;
function startTimer(){
console.log('start timer', intervalObj)
if(intervalObj === 0){
intervalObj = setInterval(callback, INTERVAL)
}
}
function stopTimer(){
clearInterval(intervalObj);
intervalObj = 0;
console.log('timer stopped', intervalObj);
}
return {
startTimer : startTimer,
stopTimer : stopTimer
}
};
</script>
</body>
</html>
回答by ihsandulu
Just Example
只是例子
var myVar
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function myStopFunction() {
clearInterval(myVar);
}
function myStartFunction() {
myVar = setInterval(myTimer, 1000);
}
myStartFunction();
<p id="demo"></p>
<button onclick="myStopFunction()">Stop time</button>
<button onclick="myStartFunction()">Start time</button>
回答by Greg Herbowicz
Wrap setInterval
in a function, for example:
包裹setInterval
在一个函数中,例如:
const startTimer = (timer) => {
let seconds = 10
timer = setInterval(() => {
console.log(seconds)
seconds--
if(seconds === 0) {
console.log("Time's up")
clearInterval(timer)
}
}, 1000)
}
and call it wherever you want:
并在任何你想要的地方调用它:
startTimer()
startTimer()