Home Web Front-end JS Tutorial Differences between setTimeout and setInterval in different browsers_javascript skills

Differences between setTimeout and setInterval in different browsers_javascript skills

May 16, 2016 pm 06:35 PM
setinterval settimeout

. (Newbies may think that setTimeout and setInterval are javascript functions, which is wrong. Newbies can easily confuse javascript object functions with DOM object methods.)

Let’s start with a piece of code. Guess what it looks like under various browsers. What will the result be?

Copy code The code is as follows:

function f(){
var s = ' arguments.length:' arguments.length '; ';
for(var i=0,n=arguments.length;i< n;i ){
s = ' [' i ']:' arguments[ i] '; ​​';
}
alert(s);
}
setTimeout(f,500,"javascript","AAA")

I am here What we want to discuss is not when to use which one, but the differences between these two methods in each browser.
Originally, I never thought that these two methods would have any consequences. I learned about them by chance. Now I have sorted them out and written them down to share with you.
Because the parameters and usage of setTimeout and setInterval are the same, but the functions are different, so to save trouble, I will only use setTimeout as an example to explain and give examples.
The most commonly used forms of setTimeout are probably as follows:
Copy code The code is as follows:

iTimerID = setTimeout(strJsCode, 50) //strJsCode is a string containing js code
iTimerID = setTimeout(objFunction, 50) //objFunction is a function object

The first calling method is to pass a string containing js code. The advantage of this method is that it is concise, but the disadvantage is that it has poor operating efficiency, is not conducive to syntax analysis, has potential risks, and more importantly, the processing is more complicated. The content is more laborious, which is consistent with the disadvantages of eval.
So, we believe that it is usually better to use the second method of calling. (My examples below all use the second calling method)

Now let’s reveal the results of the first piece of code under various browsers:
IE(6,7,8) is: arguments. length:0;
Opera(6,7,8) is: arguments.length:2; [0]:javascript; [1]:AAA;
Firefox(3.0) is: arguments.length:3; [0]:javascript; [1]:AAA; [2]:-15;
There is such a big difference, it is really "you sing your song, I hum mine"!
Under Firefox (3.0), the last number obtained is not specific. Sometimes it is 0, sometimes it is a negative number. We will discuss this issue later.
(1) setTimeout in the IE series
First, let’s take a look at what the DHTML reference manual published by Microsoft says:
setTimeout Method
Evaluates an expression after a specified number of milliseconds has elapsed .
Syntax
iTimerID = window.setTimeout(vCode, iMilliSeconds [, sLanguage])
Parameters
vCode Required. when the specified interval has elapsed.
iMilliSeconds Required. Integer that specifies the number of milliseconds.
sLanguage Optional. String that specifies one of the following values:
JScript Language is JScript.
VBScript Language is VBScript.
JavaScript Language is JavaScript.
Instructions on setTimeout on MSDN:
http://msdn.microsoft.com/en-us/library/ms536753(VS.85).aspx
In other words, setTimeout receives 3 parameters. The third parameter indicates the type of scripting language. If you pass in more parameters, it is meaningless.
So, in IE, both of the following are correct.
setTimeout('alert(1)', 50);
setTimeout('msgbox "Terminate, retry, ignore, it's up to you.", vbAbortRetryIgnore vbDefaultButton2, "Tell you"', 50, ' VBScript');
(2) setTimeout in the Mozilla series
Let’s take a look at what the Gecko DOM Reference manual on the Mozilla official website says:
window.setTimeout
Summary
Executes a code snippet or a function after specified delay.
Syntax
var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
var timeoutID = window.setTimeout(code, delay);
The first two parameters are the same, there is no difference, but the third parameter is different.
Because currently only IE browser supports scripts in multiple languages, other browsers only support js scripts, so there is no need to pass language type parameters.
Mozilla passes the third and subsequent parameters passed to setTimeout to the previous func as parameters in sequence.
The same is true for Firefox, Opera, Safari, Chrome, etc.
But I noticed that Mozilla said that its setTimeout has a bug called "Lateness" argument.
"Lateness" argument
Functions invoked by setTimeout are passed an extra "lateness" argument in Mozilla,
i.e., the lateness of the timeout in milliseconds. (See bug 10637 and bug 394769.)
This is the source of an own number in Firefox (3.0) in the example at the beginning.
Instructions on setTimeout on Mozilla:
https://developer.mozilla.org/en/DOM/window.setTimeout
(3) setTimeout in other browser series (Opera, Safari, Chrome)
Basically the same as the one in the Mozilla series, but there is no bug with one extra parameter in the Mozilla series.

Wulin Gaiden: Tips for using setTimeout
(1) Calling setTimeout in IE Function passing parameters
From the above analysis, we can see that IE does not support passing parameters to the called function in setTimeout. For the sake of harmony in the browser world, we can wrap the function calling parameters into a new anonymous function. Example:

Copy code The code is as follows:
function f(a){
alert (a);
}
// setTimeout(f,50,'hello'); //For non-IE
setTimeout(function(){f('hello')},50); //General
var str='hello';
setTimeout(function(){f(str)},50); //General

(2)this question
The context when the function called by setTimeout is executed is the global context, not the context when the setTimeout method is called. Therefore, when the function with the first parameter of setTimeout is executed, its this points to the window. If you need to retain this when calling the setTimeout method, you need to pass this in. Example:

Copy code The code is as follows:

function Person(name){
this.name=name;
var f=function(){alert('My name is ' this.name)};
// setTimeout (f,50); //Error
var THIS=this;
setTimeout(function(){f.apply(THIS)},50); //Correct, universal
setTimeout(function() {f.call(THIS)},50); //Correct, universal
}
new Person('Jack');

That's all.
Posting is not a mental job, it is actually a physical job, organizing text, writing examples, and formatting. These non-technical things are the most tiring and time-consuming.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between settimeout and setinterval What is the difference between settimeout and setinterval Aug 15, 2023 pm 02:06 PM

The difference between settimeout and setInterval: 1. Trigger time, settimeout is one-time, it executes the function once after setting the delay time, while setinterval is repetitive, it will execute the function repeatedly at the set time interval; 2. Execution times, settimeout is only executed once, and setinterval will be executed repeatedly until canceled.

How to use setInterval function to execute code regularly? How to use setInterval function to execute code regularly? Nov 18, 2023 pm 05:00 PM

How to use setInterval function to execute code regularly? In JavaScript, the setInterval function is a very useful function, which can execute a piece of code regularly. Through the setInterval function, we can repeatedly execute specified code within a specific time interval. This article will introduce in detail how to use the setInterval function and provide specific code examples. 1. The basic syntax of the setInterval function is as follows: setInterv

How to use the Window.setInterval() method How to use the Window.setInterval() method Aug 31, 2023 am 09:33 AM

The basic syntax of the Window.setInterval() method is "window.setInterval(function, delay)", function is the function or code block to be executed repeatedly, and delay is the time interval between each execution, in milliseconds. This method is a method in JavaScript used to repeatedly execute a specified function or code at a scheduled time. Its use is very simple. You only need to pass in the function or code block to be executed and the time interval for repeated execution.

How to stop setInterval How to stop setInterval Dec 11, 2023 am 11:39 AM

You can use the clearInterval function to stop a timer created by the setInterval function. The setInterval function returns a unique timer ID, which can be passed as a parameter to the clearInterval function to stop the execution of the timer.

setInterval setInterval Aug 02, 2023 am 10:17 AM

The setInterval function is a timer function in JavaScript that allows you to set an interval and execute specified code after each interval. It is very useful when certain tasks need to be processed regularly or page elements are updated in real time. Pay attention to the following when using setInterval performance and reliability issues and optimize as needed.

Detailed explanation of setinterval usage Detailed explanation of setinterval usage Sep 12, 2023 am 09:55 AM

The usage of setinterval is "setInterval(function, delay);", "function" is the function to be executed, which can be a function expression or function reference, and "delay" is the time interval between executing functions, in milliseconds. setInterval is a function in JavaScript that is used to execute code periodically. It accepts a function and a time interval as parameters, and will execute the function repeatedly according to the specified time interval.

What is the difference between setTimeout() and setInterval() in JavaScript? What is the difference between setTimeout() and setInterval() in JavaScript? Sep 01, 2023 pm 03:01 PM

setTimeout(function,duration) - This function calls the function after duration milliseconds. This works for one execution. Let's see an example - it waits for 2000 milliseconds and then runs the callback function alert('Hello') - setTimeout(function(){alert('Hello');},2000); setInterval(function,uration) - this function is The function is called after every duration milliseconds. This can be done an unlimited number of times. Let's see an example - it triggers an alarm every 2000 ms

Use the clearTimeout function in JavaScript to cancel the setTimeout timer Use the clearTimeout function in JavaScript to cancel the setTimeout timer Nov 18, 2023 am 08:05 AM

To use the clearTimeout function in JavaScript to cancel the setTimeout timer, you need specific code examples. In JavaScript, the setTimeout function is used to execute a specific code after a specified time delay. The setInterval function is used to repeatedly execute a specific code within a specified time interval. However, in some cases we may need to cancel the timer before it executes. In this case, you can use c

See all articles