clearInterval()
Функция clearInterval() отменяет многократные повторения действий, установленные вызовом функции setInterval().
Примечание: значение идентификатора, возвращённого функцией setInterval() , используется в качестве параметра для clearInterval() .
Чтобы иметь возможность использовать функцию clearInterval() , нужно использовать переменную для хранения значения, возвращаемого setInterval() : Затем, если функция уже была вызвана на исполнение, можно остановить её, вызвав clearInterval() .
JavaScript clearInterval()
The clearInterval function in javascript is used to stop the event of the recurring calling of a function at a fixed delay set by the setInterval() function. This function can be used only when a setInterval() function is previously used.
Syntax of JavaScript clearInterval()
The syntax of clearInterval() function is,
Parameters of JavaScript clearInterval()
- We must pass a single parameter ID while calling the clearInterval() function.
- The ID represent the random event number returned by the setInterval() function.
- The clearInterval() function depends on setInterval() function which has the following syntax,
- The time_delay should be given in microseconds. For example, 3000 microseconds will be 3 seconds.
- The setInterval() will call the function repeatedly periodically with a delay of value, time_delay .
- This function returns a random number assigned to the generated event.
Return Value of JavaScript clearInterval()
The clearinterval javascript function has no return value and hence returns undefined .
The undefined is a primitive data type in javascript which is used to represent nothing or no value.
Exceptions of JavaScript clearInterval()
- The clearInterval() function needs the ID of the setInterval() function to work. It becomes hard to implement the clearInterval() function if the ID is not known or the ID is changed by calling setInterval function multiple times.
- On calling the setInterval() function for the first time it returns a random number as ID, and when the function is called again, the ID is just incremented
Consider the following example, in which a setInterval() function is called continuously two times. When the function is called multiple times, the ID value returned by the previous functions will be lost and we will not be able to use the clearinterval javascript method to clear that event generated by the setInterval() function
In the above example, we have called the callSetInterval() function two times continuously, which has led to the loss of the id 24 returned by the first function call. Hence, the first event generated by the function with id 24 can't be cleared by the clearInterval() function.
The output for the following code will be
The output depicts the execution of the PrintFunction() function even after calling the clearInterval() function.
To solve the above problem, all the ID returned by the setInterval() function can be stored in an array, and the clearInterval() function is called on each element of the array separately. This is illustrated in the following example,
The clearInterval() function will not cause any error if the ID previously cleared. Therefore, we can just call the clearInterval() function for every ID stored in the id_array . This we clear all the setInterval() functions.
Example
A simple example of using the clearinterval javascript function will be to stop a counter and run the counter again for 1 second.
- In the above example, the setCount() method is used to start the counter or call the setinterval() function which in turn calls the PrintCount() function periodically for a period of 1 second.
- The PrintCount() function increments the count variable and prints it.
- The stopCount() function calls the clearInterval() function to stop counting.
The output will be displayed with a dealy of 1 second,
How Does JavaScript clearInterval() Work?
The setInterval() function is used to form an event that runs in the background and calls a particular function with a fixed time delay.
The event is created and managed by the Worker object in javascript. The worker object runs events in the background without disturbing the interaction interface. When creating this event, the function associates the event created with an ID , which is a randomly generated number. This ID can't be modified or changed after generation.
The clearInterval() is a method used to find the event with the specified ID and remove it. It is important to note that clearInterval() is the only function that can be used to remove an event started by the setInterval() function.
More Examples
We can create a progress bar that proceeds in a fixed interval of time and can be paused by using a clearinterval javascript function. The following code illustrates this,
- The arr is used to store all the ID generated by the setInterval() function. This is then used by the clearInterval() function to destroy all clear all setInterval() functions.
- We can increase the speed of the progress bar by clicking the StartInterval button as this creates a new setInterval() method on the moveSlider function.
- The progress bar will move until width becomes equal to 100, then will call the clear_events() function to invoke clearInterval function.
- The progress bar is made to move by increasing the width of the div element with id Slider . The following output will be produced by the example,
We can also create a clock and pause the clock with the clearinterval javascript function. The following example illustrates this,
In the above example, the startClock() function is used to call the setInterval() function to generate a event which calls the ChangeTime() function every second.
The clearInterval() function is used to remove the event and hence stop the clock from changing time. In this example, the local time of the browser is captured using the Date() Object in javascript.
JavaScript метод WindowOrWorkerGlobalScope.clearInterval()
JavaScript метод clearInterval() объекта WindowOrWorkerGlobalScope отменяет повторяющееся выполнение программного кода, которое было ранее установлено вызовом метода setInterval().
Для того, чтобы задать таймер, который будет многократно выполнять функцию или указанный фрагмент кода по истечению срока заданного тайм-аута воспользуйтесь методом setInterval(). Метод setInterval() возвращает положительное целое ненулевое числовое значение, которое определяет таймер, это значение может быть передано методу clearInterval(), чтобы отменить выполнение программного кода, ранее отложенного вызовом метода setInterval().
Обращаю Ваше внимание на то, что пул идентификаторов, используемых методами setTimeout() и setInterval() являются общими, что означает, что вы можете технически использовать методы clearTimeout() и clearInterval() взаимозаменяемо. Однако для ясности вам следует избегать этого.
Поддержка браузерами
| Метод | Chrome | Firefox | Opera | Safari | IExplorer | Edge |
|---|---|---|---|---|---|---|
| clearInterval() | Да | Да | Да | Да | Да | Да |
JavaScript синтаксис:
Cпецификация
Значения параметров
| Параметр | Описание |
|---|---|
| timeoutID | Идентификатор таймаута, который вы хотите отменить. Этот идентификатор возвращается соответствующим вызовом метода setInterval(). При передаче недопустимого идентификатора исключение не создается (ничего не происходит). |
Пример использования
В этом примере с использованием атрибута событий onclick при нажатии на первую кнопку (HTML элемент <button>) вызываем функцию runCounter(), которая с использованием JavaScript метода setInterval() задает таймер, который многократно выполняет функцию showCounter() каждые 1000 миллисекунд (1 секундa).
Функция showCounter() в свою очередь инкрементирует (увеличивает на 1) значение переменной counter, с помощью метода getElementById() находит элемент с определенным глобальным атрибутом id и изменяет его содержимое значением переменной counter.
С использованием атрибута событий onclick при нажатии на вторую кнопку (HTML элемент <button>) вызываем функцию clearMyTimeOut(), которая с использованием JavaScript метода clearInterval() отменяет повторяющееся выполнение программного кода, которое было ранее установлено вызовом метода setInterval(), устанавливает значение переменной counter равное нулю и добавляет элементу <span> это содержимое.
Результат нашего примера:
Пример использования методов setInterval() и clearInterval() объекта WindowOrWorkerGlobalScope JavaScript WindowOrWorkerGlobalScope
clearInterval() global function
The global clearInterval() method cancels a timed, repeating action which was previously established by a call to setInterval() . If the parameter provided does not identify a previously established action, this method does nothing.
Syntax
Parameters
The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to setInterval() .
It’s worth noting that the pool of IDs used by setInterval() and setTimeout() are shared, which means you can technically use clearInterval() and clearTimeout() interchangeably. However, for clarity, you should avoid doing so.