当前位置:网站首页>Detailed explanation of settimeout() and setinterval()
Detailed explanation of settimeout() and setinterval()
2022-06-30 14:32:00 【Domineering ape General Manager】
JavaScript It's a single-threaded language , But it can specify that the code is executed at a specific time by setting the timeout value and the interval value . A time-out value is when code is executed after a specified time , The interval time value means that the code is executed every specified time .
Timeout call
The timeout call uses window Object's setTimeout() Method , It takes two arguments : The code to execute and the time in milliseconds ( Wait time before code execution ). among , The first argument can be a string ( and eval() Same as the string used in ), It can also be a function .

The second parameter is a number of milliseconds indicating how long to wait , But the code does not necessarily execute after that time .JavaScript It's an interpreter for one line programs , So only one piece of code can be executed in a certain period of time . To control the code to be executed , There is one JavaScript Task queue . These tasks are executed in the order they are added to the task queue .setTimeout() The second parameter of tells JavaScript How long will it take to add the current task to the queue . If the queue is empty , Then the added code will be executed immediately ; If the queue is not empty , The added code will be executed after the previous code is executed .
call setTimeout() after , This method will return a value ID, Indicates a timeout call . This timeout call ID Is the unique identifier of the planned execution code , It can be used to cancel the timeout call . Cancel timeout call using method clearTimeout();

Intermittent call
Intermittent calls are similar to timeout calls , It's just that it executes code repeatedly at specified intervals , Until the intermittent call is canceled or the page is unloaded . The way to set intermittent calls is setInterval(), The parameters it receives are the same as setTimeout() identical . Canceling an intermittent call is far more important than a timeout call .

But usually , Intermittent calls are rarely really used , Because the latter intermittent call may be called before the end of the previous intermittent call . therefore , We usually use timeout calls to simulate intermittent calls

Here are two small demo:
1、 Get the current date and let it appear in the text box , Click on “stop” The event after the button is still .( Intermittent call )
HTML Code :
<input type="text" size="50" id="clock" />
<input type="button" value="Stop" id="btn" />
JavaScript Code :
function clock(){
var time = new Date();
document.getElementById("clock").value = time;
var btn =document.getElementById("btn");
btn.onclick = function(){
clearInterval(t);
}
}
var t = setInterval(clock,1000);
2、 Use setTimeou() To achieve the effect of counting and statistics , And display the value in the text box .
HTML Code :
<input type="text" id="count" />
JavaScript Code :
var num = 0;
function startCount(){
document.getElementById("count").value = num;
num += 1;
setTimeout(startCount,1000); //setTimeout It's a timeout call , Use recursion to simulate intermittent calls
}
setTimeout(startCount,1000); //1s After execution
( This question was once my interview topic , After being cheated by it, I went through various Baidu checks , I think it's not bad , So share it with you .)
边栏推荐
- Cost forecast of PMP (BAC, EAC, etc)
- On simple code crawling Youdao translation_ 0's problem (to be solved)
- Thinkphp5 log file contains trick
- 【BUUCTF】 EasySql
- Upgrade composer self update
- Getting started with shell Basics
- PHP reverses scenarios based on code and skillfully uses debug_ backtrace()
- This editor will open source soon!
- JMeter transaction controller
- The JSON data returned from the control layer to JS has a "\" translator. How to remove it
猜你喜欢

ctfshow nodejs

Not satisfied with markdown native code block style? Try this beautify code screenshot tool~~

What network security problems are exposed when a large-scale QQ number theft event occurs?

ThinkPHP show method parameter controllable command execution

Optimization of unit test efficiency: why test programs? What are the benefits of testing?
![[observation] as the intelligent industry accelerates, why should AI computing power take the lead?](/img/61/b446a616e86247507c27390505dc6b.jpg)
[observation] as the intelligent industry accelerates, why should AI computing power take the lead?

Lifting scanning tool

Introduction to reverse commissioning - VA and RVA conversion in PE 04/07

Crypto questions

Problems in QT creator (additional unknown and error lines are listed in the debug output window)
随机推荐
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703
Complete TCP forwarding server (kernel linked list + mutex)
Error on datetime when importing SQL file from MySQL
PHP common authentication / third-party methods
Logiciel de récupération de données easyrecovery15 téléchargement
Larave8 JWT API expiration custom error return
PHP recursive multi-level classification, infinite classification
JMeter transaction controller
Notes on reverse learning in the first week of winter vacation
Mysql database foundation: stored procedures and functions
This editor will open source soon!
I love network security for new recruitment assessment
Mutex lock, read / write lock, spin lock, pessimistic lock, and optimistic lock
Solve the error in my QT_ thread_ global_ End(): 3 threads didn't exit
Use PHP to delete the specified text content in the file
ThinkPHP show method parameter controllable command execution
【Kubernetes系列】K8s设置MySQL8大小写不敏感
DiceCTF - knock-knock
Problem: wechat developer tool visitor mode cannot use this function
Why does the folder appear open in another program