简体   繁体   中英

js timeout best practice

Basiaclly I need to set a time out to run 2 functions at two different times and wanted to strucuture it right. What I was looking for is something like this:

setTimeout(function(){
    $('body').chardinJs('start');
    },3000
  );
setTimeout(function(){
    $('body').chardinJs('stop');
    },6000
  );

So it would run one method after 3sec and another after 6sec. Is this correct way or can you chain them together?

This is correct.

However you should have a look on Javascript callbacks or jQuery deferred handlers . Could be cleaner.

Of course.

function sto(el, str, tm){
  setTimeout(function(){
    $(el).chardinJs(str);
    },tm
  );
}
sto('body', 'start', 3000);
sto('body', 'stop', 6000);

another would be so much longer ( setInterval, [switch] or [if] )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM