JavaScript Pills - 1. Taking a napsteemCreated with Sketch.

in #coding6 years ago (edited)

How can you "pause" the execution of a script in JavaScript?

A clean way to do so is by using await and async. Example:

async function foo() { 
    while(true) { 
     console.log('Doing stuff..'); 
     await nap(1000); 
   } 

function nap(durationMs) { 
  console.log('Taking a nap..'); 
  return new Promise(resolve => setTimeout(() => { 
     console.log('Pause is over!'); 
     resolve(); 
   }, durationMs));  

foo();



Let's say that you want to execute a bunch of http calls adding a delay after each call, how can you achieve that instead?

One of the possible ways is to use setInterval. Example:

const execCall = (idx) => {
   console.log('Executing HTTP call ', idx);
   fetch(
     'https://api.jsonbin.io/b/JSON_BIN_GENERATED_ID_HERE',
     // See https://jsonbin.io - free json storage
     {
       body:JSON.stringify({
         time: new Date().getTime(),
         data: 'Your Data'
       }),
       headers:{ 'content-type': 'application/json' },
       method: 'PUT',
       mode: 'cors',
     }
   ).then(resp => resp.json())
     .then(myJson => console.log(myJson))
     .catch(e => console.log(e));
}

const arr = [1,2,3];
let idx = 0;
setInterval(() => idx < arr.length && execCall(idx++), 2000);

If you need to stop the task you can then use

clearInterval(ID);

where ID is the integer returned when setInterval was executed




OTHER JAVASCRIPT ARTICLES:


Taking a nap
Scraping an email provider
Download files programmatically + XSS
Take screenshots programmatically

Sort:  

This post has received a 3.13 % upvote from @drotto thanks to: @valentin86.

@resteemator is a new bot casting votes for its followers. Follow @resteemator and vote this comment to increase your chance to be voted in the future!

This post was resteemed for FREE, by @rcr.bis Resteem Service.

Follow @rcr.bis to have your posts upvoted and resteemed plus a chance to win @steembasicincome shares.

This week you have a chance to win free @dustsweeper accounts

Coin Marketplace

STEEM 0.17
TRX 0.13
JST 0.030
BTC 56609.34
ETH 2990.64
USDT 1.00
SBD 2.16