簡體   English   中英

在 JavaScript 中停止 setInterval 調用

[英]Stop setInterval call in JavaScript

我正在使用setInterval(fname, 10000); 在 JavaScript 中每 10 秒調用一次 function。是否可以在某些事件中停止調用它?

我希望用戶能夠停止重復刷新數據。

setInterval()返回一個間隔 ID,您可以將其傳遞給clearInterval()

var refreshIntervalId = setInterval(fname, 10000);

/* later */
clearInterval(refreshIntervalId);

請參閱setInterval()clearInterval()的文檔。

如果將setInterval的返回值設置為變量,則可以使用clearInterval停止它。

var myTimer = setInterval(...);
clearInterval(myTimer);

您可以設置一個新變量,並在每次運行時將其遞增 ++(向上計數),然后我使用條件語句來結束它:

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>

已經回答...但是如果您需要一個特色的、可重復使用的計時器,它還支持不同時間間隔的多個任務,您可以使用我的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()

在這里查看更多

clearInterval() 方法可用於清除使用 setInterval() 方法設置的計時器。

setInterval 總是返回一個 ID 值。 可以在 clearInterval() 中傳遞此值以停止計時器。 這是一個從 30 開始並在變為 0 時停止的計時器示例。

  let time = 30;
  const timeValue = setInterval((interval) => {
  time = this.time - 1;
  if (time <= 0) {
    clearInterval(timeValue);
  }
}, 1000);

@cnu,

您可以停止間隔,在查看控制台瀏覽器(F12)之前嘗試運行代碼...嘗試評論 clearInterval(trigger) 再次查看控制台,而不是美化器? :P

檢查示例來源:

 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>

這就是我使用 clearInterval() 方法在 10 秒后停止計時器的方式。

 function startCountDown() { var countdownNumberEl = document.getElementById('countdown-number'); var countdown = 10; const interval = setInterval(() => { countdown = --countdown <= 0 ? 10 : countdown; countdownNumberEl.textContent = countdown; if (countdown == 1) { clearInterval(interval); } }, 1000) }
 <head> <body> <button id="countdown-number" onclick="startCountDown();">Show Time </button> </body> </head>

在 nodeJS 中,您可以在 setInterval function 中使用“ this ”特殊關鍵字。

您可以使用關鍵字來清除Interval,這是一個示例:

setInterval(
    function clear() {
            clearInterval(this) 
       return clear;
    }()
, 1000)

當您在 function 中打印特殊關鍵字的值時,您將輸出超時 object Timeout {...}

聲明變量以分配從 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);
}

清除間隔()

請注意,您可以使用此功能啟動和暫停您的代碼。 這個名字有點欺騙性,因為它說的是 CLEAR,但它並沒有清除任何東西。 它實際上暫停了。

使用此代碼進行測試:

HTML:

<div id='count'>100</div>
<button id='start' onclick='start()'>Start</button>
<button id='stop' onclick='stop()'>Stop</button>

JavaScript:

 let count; function start(){ count = setInterval(timer,100) /// HERE WE RUN setInterval() } function timer(){ document.getElementById('count').innerText--; } function stop(){ clearInterval(count) /// here we PAUSE setInterval() with clearInterval() code }

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>

注意:該間隔仍將執行,但是什么也不會發生。

使用 setTimeOut 在一段時間后停止間隔。

var interVal = setInterval(function(){console.log("Running")  }, 1000);
 setTimeout(function (argument) {
    clearInterval(interVal);
 },10000);

很多人都給出了很好的答案, clearInterval<\/code>是正確的解決方案。

但我認為我們可以做更多,讓我們的編輯器使用 javascript 計時器強制執行最佳實踐。

忘記清除由setTimeout<\/code>或setInterval<\/code>設置的計時器總是很容易,這可能會導致難以發現的錯誤。

所以我為上面的問題創建了一個 eslint 插件。

https:\/\/github.com\/littlee\/eslint-plugin-clean-timer<\/a>

我想下面的代碼會有所幫助:

var refreshIntervalId = setInterval(fname, 10000);

clearInterval(refreshIntervalId);

嘗試

詭計

setInterval返回一個數字:

在此處輸入圖像描述

解決方案

拿這個號碼。 將它傳遞給 function clearInterval就安全了:

在此處輸入圖像描述

代碼:

始終將返回的setInterval數存儲在變量中,以便稍后可以停止間隔:

const intervalID = setInterval(f, 1000);

// Some code

clearInterval(intervalID);

(將此數字視為setInterval的 ID。即使您調用了很多setInterval ,您仍然可以通過使用適當的 ID 來停止其中任何一個。)

 var interval = setInterval(timer, 100); var n = 0; function timer() { n = n + 0.1 document.getElementById('show').innerHTML = n.toFixed(2) } function pause() { clearInterval(interval) } function resume(){ interval = setInterval(timer, 100) }
 <h1 id="show">0</h1> <button id="btn" onclick="pause()">STOP</button> <button id="btn" onclick="resume()">RESUME</button>

為什么不使用更簡單的方法? 添加一個 class

只需添加一個 class 告訴間隔不要做任何事情。 例如:在 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">&nbsp </p> <button id="pauseInterval">Pause</button></p>

多年來,我一直在尋找這種快速簡便的方法,因此我發布了幾個版本,以向盡可能多的人介紹它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM