Search code examples
javascriptnode.jswhatsapp

Delay only working 1 time in foreach loop (whatsapp.js)


I am making a WhatsApp bot using WhatsApp Web.js, and I am sending bulk messages to my contact.

I have saved numbers in number.js but I want to add a delay in foreach to avoid getting banned by WhatsApp, but it only works one time.

There are two numbers in my array, there should be a 20 second delay between them, but there is only a delay while sending the first message. Then, both messages are sent together.

All help is appreciated.

const sleep = ms => new Promise(r => setTimeout(r, ms))

const smsg = () => {

    Numbers.forEach(async (item) => {



        let final_num = item.substring(1);
        let currnum = 1;
        let count = currnum;

        const messagetosend = "hello";
        let getuser = await user.getNumberId(final_num);
        if (getuser) {
            
            await sleep(20000)
            var newn = count + 1
            let currnum = newn
            console.log(currnum)
            console.log('Message sent to ' + final_num)
            const msg = await user.sendMessage(getuser._serialized, messagetosend)
            

        }
        else { console.log("Number not found") };

    })

}
user.on('message', message => {
    if (message.body === '!start 2005') {
        smsg()
    }
});


user.initialize();

Solution

  • Array methods, be default (se further info below) does not support async functions, so the easiest solution is to replace your forEach with a for...of-loop an make your smsg function async:

    const smsg = async () => {
    
        for(let item of Numbers){ ...do async stuff, await...
    

    However you can make array methods like forEach (and map, reduce, every etc) support async, I've written an answer about that here:

    Best way to call an asynchronous function within map?