JavaScript에서 setInterval 호출 중지
-
01-07-2019 - |
문제
나는 사용하고있다 setInterval(fname, 10000);
JavaScript에서 10초마다 함수를 호출합니다.일부 이벤트에서 호출을 중지할 수 있나요?
사용자가 반복되는 데이터 새로 고침을 중지할 수 있기를 원합니다.
해결책
setInterval()
전달할 수 있는 간격 ID를 반환합니다. clearInterval()
:
var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
다음에 대한 문서를 참조하세요. setInterval()
그리고 clearInterval()
.
다른 팁
반환 값을 설정하면 setInterval
변수에 사용할 수 있습니다 clearInterval
그것을 멈추기 위해.
var myTimer = setInterval(...);
clearInterval(myTimer);
새 변수를 설정하고 실행될 때마다 ++(1씩 증가)씩 증가시킨 다음 조건문을 사용하여 변수를 종료할 수 있습니다.
var intervalId = null;
var varCounter = 0;
var varName = function(){
if(varCounter <= 10) {
varCounter++;
/* your code goes here */
} else {
clearInterval(intervalId);
}
};
$(document).ready(function(){
intervalId = setInterval(varName, 10000);
});
도움이 되기를 바라며 정답입니다.
위의 답변에서는 setInterval이 핸들을 반환하는 방법과 이 핸들을 사용하여 Interval 타이머를 취소하는 방법을 이미 설명했습니다.
몇 가지 아키텍처 고려 사항:
"범위가 없는" 변수를 사용하지 마십시오.가장 안전한 방법은 DOM 객체의 속성을 사용하는 것입니다.가장 쉬운 곳은 "문서"일 것입니다.시작/중지 버튼으로 새로 고침을 시작하는 경우 버튼 자체를 사용할 수 있습니다.
<a onclick="start(this);">Start</a>
<script>
function start(d){
if (d.interval){
clearInterval(d.interval);
d.innerHTML='Start';
} else {
d.interval=setInterval(function(){
//refresh here
},10000);
d.innerHTML='Stop';
}
}
</script>
함수는 버튼 클릭 핸들러 내부에 정의되어 있으므로 다시 정의할 필요가 없습니다.버튼을 다시 클릭하면 타이머가 다시 시작될 수 있습니다.
이미 답변했습니다...하지만 서로 다른 간격으로 여러 작업을 지원하는 재사용 가능한 기능이 있는 타이머가 필요한 경우 내 도구를 사용할 수 있습니다. 작업타이머 (노드 및 브라우저용).
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (omit for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
// stop the timer anytime you like
if (someCondition()) timer.stop();
// or simply remove this task if you have others
if (someCondition()) timer.remove(task.id);
}
});
// Start the timer
timer.start();
귀하의 경우 사용자가 데이터 새로 고침을 방해하기 위해 클릭하는 경우;너도 전화할 수 있어 timer.pause()
그 다음에 timer.resume()
다시 활성화해야 하는 경우.
보다 여기에 더.
@cnu,
콘솔 브라우저(F12)를 보기 전에 코드를 실행하면 간격을 중지할 수 있습니다.코멘트를 사용해 보세요.clearInterval(trigger)는 미화 도구가 아닌 콘솔을 다시 살펴보는 것입니까?:피
예제 소스를 확인하세요:
var trigger = setInterval(function() {
if (document.getElementById('sandroalvares') != null) {
document.write('<div id="sandroalvares" style="background: yellow; width:200px;">SandroAlvares</div>');
clearInterval(trigger);
console.log('Success');
} else {
console.log('Trigger!!');
}
}, 1000);
<div id="sandroalvares" style="background: gold; width:200px;">Author</div>
setInterVal (...)에서 반환 된 값을 할당하고 할당 된 변수를 clearInterVal ()로 전달하도록 변수를 할당하십시오.
예를 들어
var timer, intervalInSec = 2;
timer = setInterval(func, intervalInSec*1000, 30 ); // third parameter is argument to called function 'func'
function func(param){
console.log(param);
}
// 접근 가능한 모든 곳 시간제 노동자 위에서 선언한 ClearInterval 호출
$('.htmlelement').click( function(){ // any event you want
clearInterval(timer);// Stops or does the work
});
ClearInterval() 메서드는 setInterval() 메서드로 설정된 타이머를 지우는 데 사용할 수 있습니다.
setInterval은 항상 ID 값을 반환합니다.이 값은 타이머를 중지하기 위해 ClearInterval()에 전달될 수 있습니다.다음은 30부터 시작하여 0이 되면 멈추는 타이머의 예입니다.
let time = 30;
const timeValue = setInterval((interval) => {
time = this.time - 1;
if (time <= 0) {
clearInterval(timeValue);
}
}, 1000);
var keepGoing = true;
setInterval(function () {
if (keepGoing) {
//DO YOUR STUFF HERE
console.log(i);
}
//YOU CAN CHANGE 'keepGoing' HERE
}, 500);
ID가 "stop-interval"인 버튼에 이벤트 리스너를 추가하여 간격을 중지할 수도 있습니다.
$('buuton#stop-interval').click(function(){
keepGoing = false;
});
HTML:
<button id="stop-interval">Stop Interval</button>
메모:간격은 계속 실행되지만 아무 일도 일어나지 않습니다.
더 간단한 접근 방식을 사용하면 어떨까요?수업을 추가하세요!
간격에 아무것도 하지 않도록 지시하는 클래스를 추가하기만 하면 됩니다.예를 들어:호버에.
var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause</button></p>
저는 오랫동안 이 빠르고 쉬운 접근 방식을 찾고 있었기 때문에 가능한 한 많은 사람들에게 소개하기 위해 여러 버전을 게시하고 있습니다.