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

Solution to transparent font problem after turning on ClearType in IE

The solution to the transparent font problem after...

WeChat applet implements countdown for sending SMS verification code

This article shares the specific code for the WeC...

Learn Node.js from scratch

Table of contents url module 1.parse method 2. fo...

IE6 BUG and fix is ​​a preventive strategy

Original article: Ultimate IE6 Cheatsheet: How To...

How to update v-for in Vue

Tips: Array change method will cause v-for to upd...

Design Story: The Security Guard Who Can't Remember License Plates

<br />In order to manage the vehicles enteri...

Detailed explanation of the relationship between Vue and VueComponent

The following case reviews the knowledge points o...

Some parameter descriptions of text input boxes in web design

<br />In general guestbooks, forums and othe...

How to remove the dividing line of a web page table

<br />How to remove the dividing lines of a ...

Detailed example of MySQL subquery

Subquery Classification Classification by returne...

How to build a K8S cluster and install docker under Hyper-V

If you have installed the Win10 system and want t...

A brief analysis of the game kimono memo problem

Today, after the game was restarted, I found that...

VMWare Linux MySQL 5.7.13 installation and configuration tutorial

This article shares with you the tutorial of inst...