Js how to stop setinterval
Js how to stop setinterval
Stop setInterval call in JavaScript
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.
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
setInterval() returns an interval ID, which you can pass to clearInterval() :
If you set the return value of setInterval to a variable, you can use clearInterval to stop it.
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:
I hope that it helps and it is right.
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).
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.
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:
When you print the value of this special keyword within the function you outpout a Timeout object Timeout
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.
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.
How to stop a setInterval call
I have two HTML buttons. First button starts the JavaScript function below:
Works great. I want the second button to end the setInterval. I tried like this:
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You need to declare it outside and separate the assignment. Set the interval inside:
refresh is confined into the scope of generations()
You have to make refresh global or let it be passed to stop() as parameter
In your code the «refresh» variable is local only to the function it is located. If you to keep it in this manner you should do something like this:
Scopes in Javascript
There are two different scopes available in Javascript, the first of which is called local scope and the second of which is called global scope. A scope defines how much access other functions have to a variable. Here’s how it works (in essence):
Note that commonly we like to call variables in the local scope local variables and variables in the global scope global variables.
In your code
An example of how your new code would look (this solves your problem):
Планирование: setTimeout и setInterval
Мы можем вызвать функцию не в данный момент, а позже, через заданный интервал времени. Это называется «планирование вызова».
Для этого существуют два метода:
Эти методы не являются частью спецификации JavaScript. Но большинство сред выполнения JS-кода имеют внутренний планировщик и предоставляют доступ к этим методам. В частности, они поддерживаются во всех браузерах и Node.js.
setTimeout
Например, данный код вызывает sayHi() спустя одну секунду:
Если первый аргумент является строкой, то JavaScript создаст из неё функцию.
Это также будет работать:
Но использование строк не рекомендуется. Вместо этого используйте функции. Например, так:
Начинающие разработчики иногда ошибаются, добавляя скобки () после функции:
Отмена через clearTimeout
Синтаксис для отмены:
В коде ниже планируем вызов функции и затем отменяем его (просто передумали). В результате ничего не происходит:
Повторюсь, что нет единой спецификации на эти методы, поэтому такое поведение является нормальным.
Для браузеров таймеры описаны в разделе таймеров стандарта HTML5.
setInterval
Метод setInterval имеет такой же синтаксис как setTimeout :
Все аргументы имеют такое же значение. Но отличие этого метода от setTimeout в том, что функция запускается не один раз, а периодически через указанный интервал времени.
Следующий пример выводит сообщение каждые 2 секунды. Через 5 секунд вывод прекращается:
Так что если вы запустите код выше и подождёте с закрытием alert несколько секунд, то следующий alert будет показан сразу, как только вы закроете предыдущий. Интервал времени между сообщениями alert будет короче, чем 2 секунды.
Вложенный setTimeout
Есть два способа запускать что-то регулярно.
Например, необходимо написать сервис, который отправляет запрос для получения данных на сервер каждые 5 секунд, но если сервер перегружен, то необходимо увеличить интервал запросов до 10, 20, 40 секунд… Вот псевдокод:
А если функции, которые мы планируем, ресурсоёмкие и требуют времени, то мы можем измерить время, затраченное на выполнение, и спланировать следующий вызов раньше или позже.
Сравним два фрагмента кода. Первый использует setInterval :
Второй использует вложенный setTimeout :
Для setInterval внутренний планировщик будет выполнять func(i) каждые 100 мс:
Реальная задержка между вызовами func с помощью setInterval меньше, чем указано в коде!
Вполне возможно, что выполнение func будет дольше, чем мы ожидали, и займёт более 100 мс.
В данном случае движок ждёт окончания выполнения func и затем проверяет планировщик и, если время истекло, немедленно запускает его снова.
Ниже представлено изображение, показывающее процесс работы рекурсивного setTimeout :
Вложенный setTimeout гарантирует фиксированную задержку (здесь 100 мс).
Это потому, что новый вызов планируется в конце предыдущего.
Есть и побочный эффект. Функция ссылается на внешнее лексическое окружение, поэтому пока она существует, внешние переменные существуют тоже. Они могут занимать больше памяти, чем сама функция. Поэтому, если регулярный вызов функции больше не нужен, то лучше отменить его, даже если функция очень маленькая.
setTimeout с нулевой задержкой
Это планирует вызов func настолько быстро, насколько это возможно. Но планировщик будет вызывать функцию только после завершения выполнения текущего кода.
Так вызов функции будет запланирован сразу после выполнения текущего кода.
Например, этот код выводит «Привет» и затем сразу «Мир»:
Первая строка помещает вызов в «календарь» через 0 мс. Но планировщик проверит «календарь» только после того, как текущий код завершится. Поэтому «Привет» выводится первым, а «Мир» – после него.
Есть и более продвинутые случаи использования нулевой задержки в браузерах, которые мы рассмотрим в главе Событийный цикл: микрозадачи и макрозадачи.
В браузере есть ограничение на то, как часто внутренние счётчики могут выполняться. В стандарте HTML5 говорится: «после пяти вложенных таймеров интервал должен составлять не менее четырёх миллисекунд.».
Аналогичное происходит при использовании setInterval вместо setTimeout : setInterval(f) запускает f несколько раз с нулевой задержкой, а затем с задержкой 4+ мс.
Это ограничение существует давно, многие скрипты полагаются на него, поэтому оно сохраняется по историческим причинам.
Этого ограничения нет в серверном JavaScript. Там есть и другие способы планирования асинхронных задач. Например, setImmediate для Node.js. Так что это ограничение относится только к браузерам.
Итого
Обратим внимание, что все методы планирования не гарантируют точную задержку.
Например, таймер в браузере может замедляться по многим причинам:
Всё это может увеличивать минимальный интервал срабатывания таймера (и минимальную задержку) до 300 или даже 1000 мс в зависимости от браузера и настроек производительности ОС.
Задачи
Вывод каждую секунду
Сделайте два варианта решения.
Scheduling: setTimeout and setInterval
We may decide to execute a function not right now, but at a certain time later. That’s called “scheduling a call”.
There are two methods for it:
These methods are not a part of JavaScript specification. But most environments have the internal scheduler and provide these methods. In particular, they are supported in all browsers and Node.js.
setTimeout
For instance, this code calls sayHi() after one second:
If the first argument is a string, then JavaScript creates a function from it.
So, this will also work:
But using strings is not recommended, use arrow functions instead of them, like this:
Novice developers sometimes make a mistake by adding brackets () after the function:
Canceling with clearTimeout
A call to setTimeout returns a “timer identifier” timerId that we can use to cancel the execution.
The syntax to cancel:
In the code below, we schedule the function and then cancel it (changed our mind). As a result, nothing happens:
As we can see from alert output, in a browser the timer identifier is a number. In other environments, this can be something else. For instance, Node.js returns a timer object with additional methods.
Again, there is no universal specification for these methods, so that’s fine.
For browsers, timers are described in the timers section of HTML5 standard.
setInterval
The setInterval method has the same syntax as setTimeout :
All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.
The following example will show the message every 2 seconds. After 5 seconds, the output is stopped:
So if you run the code above and don’t dismiss the alert window for some time, then the next alert will be shown immediately as you do it. The actual interval between alerts will be shorter than 2 seconds.
Nested setTimeout
There are two ways of running something regularly.
For instance, we need to write a service that sends a request to the server every 5 seconds asking for data, but in case the server is overloaded, it should increase the interval to 10, 20, 40 seconds…
Here’s the pseudocode:
And if the functions that we’re scheduling are CPU-hungry, then we can measure the time taken by the execution and plan the next call sooner or later.
Let’s compare two code fragments. The first one uses setInterval :
The second one uses nested setTimeout :
For setInterval the internal scheduler will run func(i++) every 100ms:
The real delay between func calls for setInterval is less than in the code!
That’s normal, because the time taken by func ‘s execution “consumes” a part of the interval.
It is possible that func ‘s execution turns out to be longer than we expected and takes more than 100ms.
In this case the engine waits for func to complete, then checks the scheduler and if the time is up, runs it again immediately.
In the edge case, if the function always executes longer than delay ms, then the calls will happen without a pause at all.
And here is the picture for the nested setTimeout :
The nested setTimeout guarantees the fixed delay (here 100ms).
That’s because a new call is planned at the end of the previous one.
For setInterval the function stays in memory until clearInterval is called.
There’s a side effect. A function references the outer lexical environment, so, while it lives, outer variables live too. They may take much more memory than the function itself. So when we don’t need the scheduled function anymore, it’s better to cancel it, even if it’s very small.
Zero delay setTimeout
This schedules the execution of func as soon as possible. But the scheduler will invoke it only after the currently executing script is complete.
So the function is scheduled to run “right after” the current script.
For instance, this outputs “Hello”, then immediately “World”:
The first line “puts the call into calendar after 0ms”. But the scheduler will only “check the calendar” after the current script is complete, so «Hello» is first, and «World» – after it.
There are also advanced browser-related use cases of zero-delay timeout, that we’ll discuss in the chapter Event loop: microtasks and macrotasks.
In the browser, there’s a limitation of how often nested timers can run. The HTML5 standard says: “after five nested timers, the interval is forced to be at least 4 milliseconds.”.
Let’s demonstrate what it means with the example below. The setTimeout call in it re-schedules itself with zero delay. Each call remembers the real time from the previous one in the times array. What do the real delays look like? Let’s see:
The similar thing happens if we use setInterval instead of setTimeout : setInterval(f) runs f few times with zero-delay, and afterwards with 4+ ms delay.
That limitation comes from ancient times and many scripts rely on it, so it exists for historical reasons.
For server-side JavaScript, that limitation does not exist, and there exist other ways to schedule an immediate asynchronous job, like setImmediate for Node.js. So this note is browser-specific.
Summary
Please note that all scheduling methods do not guarantee the exact delay.
For example, the in-browser timer may slow down for a lot of reasons:
All that may increase the minimal timer resolution (the minimal delay) to 300ms or even 1000ms depending on the browser and OS-level performance settings.
Tasks
Output every second
Make two variants of the solution.
How to stop all timeouts and intervals using javascript? [duplicate]
I’m working on an ajax web appliation which contains many running timeouts and intervals. And now I need to clear all running timeouts and intervals sometimes. Is there a simple way to stop everything without need to store every timeout and interval ID and iterate through them and clear them?
10 Answers 10
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Sometimes it’s possible to save the timer Id / Handle to clear it later which would be the best solution. So this is a second best. But I wanted to give a better understanding of what’s going on. It basically grabs the highest timer id and clears everything less than that. But it’s also possible to clear other timers that you do not want to clear!
It is a little hackish, so be warned!
It works and tested in Chrome on OSX
Here is a workaround.
It works for set/clear timeout/interval functions called after these lines are executed. Try and see it works:
Proxying does the magic.
There’s nothing built-in, but it’s pretty easy to blast through all currently outstanding deferred execution functions by calling this clearAll() function:
To try that it works, you could then try doing this, for instance, which will remain silent, as none of the callbacks end up firing before they’re cancelled again:
If you are using third party libraries which uses Timeouts and Intervals then they will also be cleared, so I added one parameter to notify function that this interval is to be push ‘ed or not to array.
You might be better off creating a scheduler. Take a look at this approach by Nader Zeid:
It’s an approach that help create some determinacy (because «the time interval argument of each of those functions really only establishes that the given function will execute after at least that amount of time. So a timed event can miss its target by literally any amount of time.»).
Specifically, to the question you raise here, you can easily add and remove functions from the queue. While this response is long after the question was raised, hopefully it’s helpful to any who find themselves struggling with Timeouts and Intervals.