停止 JavaScript 中的 setInterval 调用

发布于 2025-01-18 18:18:00 字数 117 浏览 3 评论 0原文

我正在使用setInterval(fname,10000);在JavaScript中每10秒调用一次功能。是否可以在某些活动中停止调用它?

我希望用户能够停止重复的数据刷新。

I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?

I want the user to be able to stop the repeated refresh of data.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

人间☆小暴躁 2025-01-25 18:18:00

setInterval()返回一个间隔ID,您可以将其传递到clearInterval()

var refreshIntervalId = setInterval(fname, 10000);

/* later */
clearInterval(refreshIntervalId);

请参阅 setInterval() and clear Interval()

setInterval() returns an interval ID, which you can pass to clearInterval():

var refreshIntervalId = setInterval(fname, 10000);

/* later */
clearInterval(refreshIntervalId);

See the docs for setInterval() and clearInterval().

你的呼吸 2025-01-25 18:18:00

如果将setInterval的返回值设置为变量,则可以使用clearInterval来停止它。

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

If you set the return value of setInterval to a variable, you can use clearInterval to stop it.

var myTimer = setInterval(...);
clearInterval(myTimer);
胡大本事 2025-01-25 18:18:00

您可以设置一个新变量,并在每次运行时都会将其递增(计数一个),然后我使用条件语句来结束它:

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);
});

我希望它有帮助并且是正确的。

You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:

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);
});

I hope that it helps and it is right.

蓝天 2025-01-25 18:18:00

已经回答了...但是如果您需要一个功能齐全、可重复使用的计时器,并且还支持不同时间间隔的多个任务,您可以使用我的 TaskTimer(适用于 Node 和浏览器)。

// 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()

请参阅更多信息

Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (for Node and browser).

// 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();

In your case, when users click for disturbing the data-refresh; you can also call timer.pause() then timer.resume() if they need to re-enable.

See more here.

℉絮湮 2025-01-25 18:18:00

技巧

setInterval 返回一个数字:

在此处输入图像描述

解决方案

获取此号码。将其传递给函数 clearInterval 即可安全:

在此处输入图像描述

代码:

始终将 setInterval 返回的数字存储在一个变量,以便您可以稍后停止间隔:

const intervalID = setInterval(f, 1000);

// Some code

clearInterval(intervalID);

(将此数字视为 setInterval 的 ID。即使您调用了多次 setInterval,您仍然可以使用正确的 ID 来停止其中任何一个。)

The Trick

setInterval returns a number:

enter image description here

Solution

Take this number. Pass it to the function clearInterval and you're safe:

enter image description here

Code:

Always store the returned number of setInterval in a variable, so that you can stop the interval later on:

const intervalID = setInterval(f, 1000);

// Some code

clearInterval(intervalID);

(Think of this number as the ID of a setInterval. Even if you have called many setInterval, you can still stop anyone of them by using the proper ID.)

囚你心 2025-01-25 18:18:00

在nodeJS中,您可以在setInterval函数中使用“this”特殊关键字。

您可以使用这个 this 关键字来清除间隔,下面是一个示例:

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

当您在函数中打印 this 特殊关键字的值时,您会输出一个 Timeout 对象 Timeout {...}

In nodeJS you can you use the "this" special keyword within the setInterval function.

You can use this this keyword to clearInterval, and here is an example:

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

When you print the value of this special keyword within the function you output a Timeout object Timeout {...}

睡美人的小仙女 2025-01-25 18:18:00
const interval = setInterval(function() {
     const checkParticlesjs = document.querySelector('.success_class')  // get success_class from page
     if (checkParticlesjs) {  // check if success_class exist
         fbq('track', 'CompleteRegistration');  // Call Facebook Event
         clearInterval(interval);  // Stop Interval 
        }
 }, 2000); // repeat every 2 second
const interval = setInterval(function() {
     const checkParticlesjs = document.querySelector('.success_class')  // get success_class from page
     if (checkParticlesjs) {  // check if success_class exist
         fbq('track', 'CompleteRegistration');  // Call Facebook Event
         clearInterval(interval);  // Stop Interval 
        }
 }, 2000); // repeat every 2 second
一笑百媚生 2025-01-25 18:18:00

如果您的计数器位于单击按钮中,请使用此选项。

<button onClick="inter = setInterval(myCounter, 1000)">start to count</button>

<p id="demo">here is the counter</p>

<button onClick="clearInterval(inter)">stop </button>

Use this if you have your counter in a button onclick.

<button onClick="inter = setInterval(myCounter, 1000)">start to count</button>

<p id="demo">here is the counter</p>

<button onClick="clearInterval(inter)">stop </button>
没有伤那来痛 2025-01-25 18:18:00

为什么不使用更简单的方法呢?添加班级!

只需添加一个类来告诉间隔不要执行任何操作。例如:悬停时。

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>

多年来我一直在寻找这种快速而简单的方法,因此我发布了多个版本以向尽可能多的人介绍它。

Why not use a simpler approach? Add a class!

Simply add a class that tells the interval not to do anything. For example: 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>

I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文