Home  >  Article  >  Web Front-end  >  Use closures to simply encapsulate setTimeout to avoid errors_javascript tips

Use closures to simply encapsulate setTimeout to avoid errors_javascript tips

WBOY
WBOYOriginal
2016-05-16 17:29:171074browse

When writing js scripts, some spelling functions are often used, such as calling setTimeout

Copy code The code is as follows:

var msgalert="test";
function TestAlert(msg)
{
alert(msg)
}

$(document).ready( function () {
$("#btnCancel").click(function (e) {
setTimeout("TestAlert(" msgalert ")",1000);
});
})

After checking for a long time, why the dialog box does not pop up. After checking for a long time, I discovered that a pair of single quotes
was missing. Copy the code The code is as follows:

$(document).ready(function () {
$("#btnCancel").click(function (e) {
setTimeout("TestAlert('" msgalert "')",1000 ; 🎜>


Copy code


The code is as follows:);
}
function TestAlert(msg)
{
alert(msg)
}

$(document).ready(function () {
$("#btnCancel").click(function (e) {
dalayAlert(msgalert,1000)
}) ;
})


Due to the use of closures, it is much simpler and it is easy to check for errors.
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