Home  >  Article  >  Web Front-end  >  Notes on the use of setInterval and setTimeout in jQuery_jquery

Notes on the use of setInterval and setTimeout in jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 18:01:431031browse

When writing timers in the past, I always used to directly

setInterval("fn()",2000);
Recently I encountered a problem. When writing timers using jquery, fn always appeared. Non-existent error message, as follows

$(function(){setInterval("fn()",2000);})
The solution is to remove the quotes and brackets and use the most original method

$(function(){setInterval(fn,2000);})
The other way is to write an extension of jq, as follows

Copy the code The code is as follows:

$(function(){
$.extend({
fn:function(){
alert(" im fn!");
}
});
setInterval("$.fn()",2000);
});

All of the above are written There is no problem. But what if you need to pass parameters?

Like the first way of writing above,

$(function(){setInterval(fn,2000);})
If written as

$(function() {setInterval(fn(para),2000);})
reported an error. This one is more classic and more idiotic.

At this time you can build in a function and write it as

$(function(){setInterval(function(){fn(para)},2000);})
This is also possible of.

As for how to deliver the second method, this is simpler, so I won’t say more.

Post it to the blog for memory use only, it’s all basic! This is also where beginners tend to make mistakes!


//==========================

Let me add the second type of parameter passing. method.

Look at the code first
Copy the code The code is as follows:

$( function(){
$start = 1;
$.extend({
a:function(t){
$index = t;
alert($index);
$start ;
}
});
setInterval("$.a(" $start ")",2000);
});

Some People would try to write like this, and what would be the result? The result is the alert, which is always 1 and will not increase. What needs to be noted here is the first parameter in setInterval. This is a statement, enclosed in double quotes, and the content inside will be interpreted as a variable. If you follow the above writing method, it is equivalent to

setInterval("$.a(1)",2000);
Then the result is understandable. The correct way to write it is of course
Copy the code The code is as follows:

$(function() {
$start = 1;
$.extend({
a:function(t){
$index = t;
alert($index);
$start;
}
});
setInterval("$.a($start)",2000);
});

At this time $start will be interpreted as variables. The statement is equivalent to function(){a(variable)}, not function(){a(value)}.
Statement:
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