推迟在JavaScript中运行的代码
在JavaScript中创建用户界面有时可能会导致问题,尤其是当界面使用AJAX从服务器加载数据时。由于用户将由事件驱动许多动作,因此您会发现,当用户一次触发很多事件时,浏览器将一次发出很多AJAX请求。这很容易引起带宽问题,但也可能导致用户在耐心等待浏览器稳定下来并让他们继续工作时感到困惑。
解决这个问题的方法有很多,第一种是设计程序,以便仅在用户单击某项内容或开始键入内容时才发出AJAX请求
However,sometimesyoucan'talwaysgetaroundthis,forexample,youmightwanttocontinuouslyvalidateainputboxastheusertypesinit.Themoststableandbrowserfriendly(nottomentionuserfriendly)methodseemstobeusingacombinationofthesetTimeOut()andclearTimeout()methods.InthiswayyoucanwaituntiltheuserhasfinishedwhattheyaredoingbeforerunningthecodethatusesAJAX.Thefollowingcodewillprintanalertbox,butonlyafteradurationof500millisecondsafterthelastonclickeventontheparagraphtag.
Run It
Thiscodelookstoseeifrunisequalto'',whichiswhatthevariablehasbeensetto,butisalsowhatthevariableissettowhenclearTimeout()iscalled.ThesetTimeout()functionwillcausetherunvariabletobefilledwithaprocessID.ThesecondparameterinthesetTimeout()functionisthenumberofmillisecondstowaitforbeforerunningthefunctionorcodedefinedinthefirstparameter.TheonlydrawbackwiththismethodisthatitisnotpossibletosendparametersalongwiththecallbackfunctionstipulatedinsetTimeout(),butthereisawayaroundthis,althoughitisabitugly.WhentherunIt()functionisrunyoucansetthevaluesofanumberofvariablesdefinedintheglobalscopethatwillthenbeusedwithinthefunctiontheiscalledafterthedelay.Thefollowingcodedemonstratesthis.
Run It
该代码将打印出用户单击p标签的次数。即使用户多次单击标签,它仍会跟踪并在最后一次单击事件后500毫秒打印该值。