JavaScript setTimeout and setTimeinterval use cases explained

JavaScript setTimeout and setTimeinterval use cases explained

Both methods can be used to execute a piece of javascript code after a fixed period of time, but each has its own application scenarios.

In fact, the syntax of setTimeout and setInterval is the same. They all have two parameters, one is the code string to be executed, and the other is the time interval in milliseconds, after which the code will be executed.

However, there is a difference between these two functions. After setInterval executes the code once, it will automatically repeat the code after a fixed time interval, while setTimeout only executes the code once.

Although it seems that setTimeout can only be applied to on-off actions, you can create a function loop to repeatedly call setTimeout to achieve repeated operations:

showTime();
function showTime()
{
    var today = new Date();
    alert("The time is: " + today.toString());
    setTimeout("showTime()", 5000);
}

Once this function is used, the time will be displayed every 5 seconds. If you use setInterval, the corresponding code is as follows:

setInterval("showTime()", 5000);
function showTime()
{
    var today = new Date();
    alert("The time is: " + today.toString());
}

These two methods may look very similar and display similar results, but the biggest difference between the two is that the setTimeout method does not execute the showTime function every 5 seconds. It executes the showTime function 5 seconds after each call to setTimeout. This means that if the main part of the showTime function takes 2 seconds to execute, then the entire function will be executed every 7 seconds. However, setInterval is not bound by the function it calls, it simply repeats the function at a certain interval.

If you need to perform an action accurately after a fixed time interval, it is best to use setInterval. If you do not want to interfere with each other due to continuous calls, especially if each function call requires heavy calculations and a long processing time, it is best to use setTimeout.

Use of function pointers

The first parameter of the two timing functions is a string of code. In fact, this parameter can also be a function pointer, but IE 5 under Mac does not support this.

If you use a function pointer as the second parameter of the setTimeout and setInterval functions, they can execute a function defined elsewhere:

setTimeout(showTime, 500);
function showTime()
{
    var today = new Date();
    alert("The time is: " + today.toString());
}

In addition, anonymous functions can also be declared as inline functions:

setTimeout(function(){var today = new Date();
alert("The time is: " + today.toString());}, 500);

discuss

If the timing function is not processed, setInterval will continue to execute the same code until the browser window is closed or the user goes to another page. However, there are still ways to terminate the execution of setTimeout and setInterval functions.

When the setInterval call is completed, it will return a timer ID, which can be used to access the timer in the future. If the ID is passed to clearInterval, the execution of the called process code can be terminated. The specific implementation is as follows:

var intervalProcess = setInterval("alert('GOAL!')", 3000);
var stopGoalLink = document.getElementById("stopGoalLink");
attachEventListener(stopGoalLink, "click", stopGoal, false);
function stopGoal()
{
    clearInterval(intervalProcess);
}

As long as stopGoalLink is clicked, no matter when it is clicked, intervalProcess will be canceled and intervalProcess will not be executed repeatedly in the future. If setTimeout is canceled within the timeout period, this termination effect can also be achieved on setTimeout, as follows:

var timeoutProcess = setTimeout("alert('GOAL!')", 3000);
var stopGoalLink = document.getElementById("stopGoalLink");
attachEventListener(stopGoalLink, "click", stopGoal, false);
function stopGoal() {
   clearTimeout(timeoutProcess);
}

This concludes this article on the detailed use cases of JavaScript setTimeout and setTimeinterval. For more relevant content on the use of js setTimeout and setTimeinterval, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript data visualization: ECharts map making
  • Super detailed basic JavaScript syntax rules
  • Detailed explanation of mandatory and implicit conversion of types in JavaScript
  • JavaScript implements changing the color of a web page through a slider
  • Detailed explanation of the differences between var, let and const in JavaScript es6
  • Detailed explanation of the this pointing problem in JavaScript
  • JavaScript function call, apply and bind method case study
  • Detailed explanation of the use of Arguments object in JavaScript
  • JavaScript CollectGarbage Function Example
  • Detailed explanation of BOM and DOM in JavaScript
  • JavaScript timer to achieve limited time flash sale function
  • JavaScript to implement limited time flash sale function
  • JavaScript Objects (details)

<<:  MySQL transaction, isolation level and lock usage example analysis

>>:  Ubuntu 19.10 enables ssh service (detailed process)

Recommend

MySQL database deletes duplicate data and only retains one method instance

1. Problem introduction Assume a scenario where a...

Ubuntu 20.04 Chinese input method installation steps

This article installs Google Input Method. In fac...

Example of how to create a database name with special characters in MySQL

Preface This article explains how to create a dat...

Detailed steps and problem solving methods for installing MySQL 8.0.19 on Linux

I recently bought a Tencent Cloud server and buil...

nginx solves the problem of slow image display and incomplete download

Written in front Recently, a reader told me that ...

Example of using mycat to implement MySQL database read-write separation

What is MyCAT A completely open source large data...

The whole process of installing and configuring Harbor1.7 on CentOS7.5

1. Download the required packages wget -P /usr/lo...

About the problem of writing plugins for mounting DOM in vue3

Compared with vue2, vue3 has an additional concep...

Cross-domain issues in front-end and back-end separation of Vue+SpringBoot

In the front-end and back-end separation developm...

Analysis of MySQL data backup and recovery implementation methods

This article uses examples to describe how to bac...