Home > Web Front-end > JS Tutorial > body text

Solution to the failure of timer (setTimeout/setInterval) calling function with parameters_javascript skills

WBOY
Release: 2016-05-16 17:39:18
Original
1380 people have browsed it

First, let’s look at the usage of timers
1. setInterval(code,millisec[,"lang"]) The setInterval() method can call functions or calculate expressions according to the specified period (in milliseconds).

参数 描述
code 必需,要调用的函数或要执行的代码串。
millisec 必需,周期性执行或调用 code 之间的时间间隔,以毫秒计。

2.setTimeout(code,millisec) The setTimeout() method is used to call a function or calculate an expression after a specified number of milliseconds.
参数 描述
code 必需,要调用的函数后要执行的 JavaScript 代码串。
millisec 必需,在执行代码前需等待的毫秒数。

Tip: setTimeout() only executes code once. If you want to call it multiple times, use setInterval() or have the code itself call setTimeout() again.
Perhaps you have encountered such a problem. Whether it is setInterval() or setTimeout(), when a function with parameters is placed in the code parameter, the timer will fail. Take a look at the following example:
Copy code The code is as follows:

function test(str){
alert(str);
}
var a = "abcde"
setTimeout(test(a),3000);

When the above code is executed, the page will not delay calling test(a) for 3 seconds, but will Execute test(a) immediately. This problem will occur under IE, FF, and Chrome. If you often use timers, you should encounter this problem often, so how to solve it?
The author summarizes two commonly used solutions here. Of course, there should be other solutions, so I won’t go into details here.
Method 1: Wrap
with anonymous function Copy code The code is as follows:

function test (str){
alert(str);
}
var a = "abcde"
setTimeout(function(){
test(a);
},3000);

Method 2: Wrap the function to be called in quotes
Copy the code The code is as follows:

function test(str){
alert(str);
}
var a = "abcde"
setTimeout("test(' a ')",3000) ;

The above only takes setTimeout() as an example, setInterval() is also applicable, so I won’t go into details here.
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!