JavaScript에서 setInterval 호출 중지
사용하고 있다setInterval(fname, 10000);
자바스크립트에서 함수를 10초마다 호출합니다.어떤 이벤트에서 그만 불러도 될까요?
나는 사용자가 반복적인 데이터 갱신을 멈출 수 있기를 바란다.
setInterval()
인터벌 ID를 반환합니다.이 ID는 에 전달할 수 있습니다.clearInterval()
:
var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
및 의 문서를 참조해 주세요.
반환값을 설정하는 경우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);
});
나는 그것이 도움이 되고 그것이 옳기를 바란다.
이미 대답했습니다...단, 다른 간격으로 여러 작업을 지원하는 재사용 가능한 기능이 있는 타이머가 필요한 경우 TaskTimer를 사용할 수 있습니다(노드와 브라우저용).
// 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()
다시 활성화해야 하는 경우.
자세한 것은 이쪽.
nodeJS에서는 setInterval 함수 내에서 "this" special 키워드를 사용할 수 있습니다.
이 키워드를 사용하면, 다음의 항목을 클리어 할 수 있습니다.Interval(간격차는 다음과 같습니다.
setInterval(
function clear() {
clearInterval(this)
return clear;
}()
, 1000)
함수 내에서 이 특별한 키워드 값을 출력하면 Timeout 객체가 출력됩니다.Timeout {...}
좀 더 심플한 접근방식을 사용하면 어떨까요?클래스를 추가합니다!
아무 것도 하지 않는 간격을 알려주는 클래스를 추가합니다.예: on hover.
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>
저는 오랫동안 이 빠르고 쉬운 방법을 찾고 있었기 때문에 가능한 한 많은 사람들을 소개하기 위해 여러 버전을 게시하고 있습니다.
언급URL : https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript
'programing' 카테고리의 다른 글
목록 초기화용 이 코드가 목록을 서로 링크하는 이유는 무엇입니까? (0) | 2022.10.19 |
---|---|
라이브러리가 로드되지 않음: mysql2 gem을 사용하여 OS X 10.6에서 'rails server'를 실행하려고 하면 libmysqlclient.16.dylib 오류가 발생함 (0) | 2022.10.19 |
node.js를 사용하여 mySQL에 대량 삽입하려면 어떻게 해야 합니까? (0) | 2022.10.19 |
각 콜백의 모든 비동기 후 콜백 (0) | 2022.10.19 |
새 폴더 작성 방법 (0) | 2022.10.19 |