2017-05-04 8 views
0

사용자가 버튼을 누를 때 setInterval을 시작하려고합니다. 버튼 ID는 #begin입니다. 다양한 방법을 시도했지만 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

당신이 JQuery와 사용

$(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

자바 스크립트 솔루션 :

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

, 당신은 버튼 클릭 이벤트가 유 코드를 공유 할 수있다

$("#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>