简体   繁体   中英

Is there a way to pause or delay an event handler in JavaScript?

I'm very new to JavaScript and trying to learn. I am using the StreamLabs API to display gif animations for Twitch alerts .

If alerts come in too quickly, the animation will keep cutting itself off and starting from the beginning. I'm trying to delay the events so that the animations will play fully.

Currently, the code snippet in question looks like this.

streamlabs.on('event', (eventData) => 
  {
    var start = new Date();
    if (eventData.for === 'twitch_account') 
    {
      switch (eventData.type) 
      {
        case 'follow':
          //code to handle follow events
          console.log(eventData.message);
          setTimeout(function()
          {
            changeWithFollow();
            setTimeout(function () 
            {
              changeToDefault()
            }, followGifLength);
          }, start % 2500);
          break;
    }
}
})

Use Promise & SetTimeout to set delay:

 function delay(millseconds) { return new Promise(resolve => { setTimeout(() => { console.log('waiting...') resolve('waiting...') }, millseconds) }) } async function test() { console.clear(); console.log('start'); await delay(2000); console.log('end'); } test();

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