2017-05-04 119 views
0

我想,当用户按下一个按钮启动的setInterval。按钮ID是#开头。我尝试了各种方法,但是然后setInterval根本不起作用。任何方式让这个工作?谢谢!开始的setInterval当按钮被点击

 $(function() { 
    count = 0; 
    wordsArray = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"]; 
    setInterval(function() { 
    count++; 
    $(".first").fadeOut(400, function() { 
     $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400); 
    }); 
    }, 5000); 
}); 
+0

哪里是你的按钮单击事件ü可以分享您的代码,我们将帮你。 – Venkatachalam

+0

请根据您的问题添加代码,并尝试用最大程度的可视化来解释您的问题 –

回答

3

$(function() { 
 
    
 
\t $('#begin').click(function(){ 
 
\t \t count = 0; 
 
    wordsArray = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"]; 
 
    setInterval(function() { 
 
    count++; 
 
    $(".first").fadeOut(400, function() { 
 
     $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400); 
 
    }); 
 
    }, 5000); 
 
\t }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="button" id="begin" value="Start" /> 
 
<div class="first"> 
 

 
</div>

0

JavaScript解决方案:

document.getElementById('button').addEventListener('click', function() { 
    setInterval(tick, 100); 
}); 

function tick() { 
    console.log('tick'); 
} 

jQuery的一个可能是这个样子:

$('#button').click(function() { 
    setInterval(tick, 100); 
}); 

好的做法是间隔存储,这样可以清除它,只要你需要:

const interval = setInterval(tick, 100); 

// Clear it this way 
clearInterval(interval); 
0

您使用JQuery,你可以添加一个回调点击动作

$("#begin").click(function(event){ 
    //start your timer like 
    var count = 0, 
    wordsArray = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"]; 
    setInterval(function() { 
    count++; 
    $(".first").fadeOut(400, function() { 
     $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400); 
    }); 
    }, 5000); 

}); 
0

$('#begin').click(function(){ 
 
\t count = 0; 
 
    wordsArray = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"]; 
 
    setInterval(function() { 
 
    count++; 
 
    $(".text_display").fadeOut(400, function() { 
 
     $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400); 
 
    }); 
 
    }, 5000); 
 
})
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
 
<button id="begin"> 
 
Submit 
 
</button> 
 

 
<div class="text_display"> 
 
</div>