0

I'm trying to create something like slide show that is moved automatically after a delay. I don't really understand how promises work so I find myself unable to create the sleep functinon. Any solutions?

const startBtn = document.querySelector('.startBtn');
const box = document.querySelector('.box')

startBtn.addEventListener('click', () => {
    for(var i = 1; i <= 20;i++){
        //sleep(60000);  <= the problem
        box.style.transform = 'translateY(' + (-i * 100) + 'vh)';
    }
});
Rentib
  • 31
  • 4
  • 5
    Does this answer your question? [What is the JavaScript version of sleep()?](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep) – HeySora Aug 31 '20 at 09:25

2 Answers2

0

Easiest you can do is use setTimeout:

setTimeout(function(){ alert("Hello"); }, 3000);

See: https://www.w3schools.com/jsref/met_win_settimeout.asp

Maybe you'll want to consider setInterval instead for your problem. In both cases you have to rework your solution a bit, the for loop won't help you much.

nsndvd
  • 770
  • 7
  • 21
0
function sleep(delay){
    return new Promise(resolve=>{
        setTimeout(resolve,delay);
    })
}

const fn = async () =>{
    let pre = new Date()
    console.log(pre);
    await sleep(2000);
    let after = new Date();
    console.log(after - pre);
}



startBtn.addEventListener('click', async() => {
    for(var i = 1; i <= 20;i++){
       // sleep i*1000 seconds
       await sleep(i* 1000);
       box.style.transform = 'translateY(' + (-i * 100) + 'vh)';
    }
});

Liu Lei
  • 1,063
  • 1
  • 7
  • 9