JavaScript setInterval: использование и примеры

JavaScript setInterval

JavaScript setInterval is a method that is used to call a function or execute code at a specified interval of time. It has two parameters: the function or code to be executed and the interval of time between each call.

Example usage of setInterval in JavaScript:

<!-- Example 1: Call a function every 2 seconds -->
<script>
  setInterval(function() {
    console.log("Hello, world!");
  }, 2000);
</script>


<!-- Example 2: Execute code every 3 seconds -->
<script>
  let counter = 0;
  setInterval(function() {
    counter++;
    console.log("Current counter value: " + counter);
  }, 3000);
</script>

In the first example, we pass an anonymous function that simply logs the message "Hello, world!" to the console. This function will be called every 2 seconds.

In the second example, we create a variable `counter` and set its value to 0. Then, we pass an anonymous function that increments the counter value by 1 and logs the current value to the console. This function will be called every 3 seconds.

setInterval is a very useful method that can be used in various scenarios. For example, it can be useful for data refreshing on a web page, polling a server for new data, or creating animations.

If you need to stop the execution of code that is invoked using setInterval, you can use the clearInterval method. It takes the timer identifier returned by setInterval and stops the execution of the function.

Example usage of clearInterval:

<script>
  let timer = setInterval(function() {
    console.log("Hello, world!");
  }, 2000);

  // Stop code execution after 10 seconds
  setTimeout(function() {
    clearInterval(timer);
  }, 10000);
</script>

In this example, we first create a timer and assign it to the `timer` variable. Then, we use the setTimeout method to stop the code execution after 10 seconds. In the callback function of the setTimeout method, we call clearInterval, passing it the timer identifier.

Thus, setInterval is a powerful tool in JavaScript that allows you to call a function or execute code at a specified interval of time. It has a wide range of applications and can be useful in many different web development scenarios.

Похожие вопросы на: "javascript setinterval "

Биржевой API Binance: возможности, документация и интеграция
Java Set: набор уникальных элементов для работы с коллекциями
Разработка на языке C с помощью инструментов JetBrains
Массивы Java: основные операции и методы
Как использовать parseInt в Java
Изучение preg_replace: замена текста с помощью PHP и регулярных выражений
PostgreSQL LIKE - поиск подстроки в базе данных
Красивое форматирование JSON
Перевод числа из десятичной системы в двоичную
Positional argument follows keyword argument