4

I would like to be able to make something similar to this:

function testFunction() {
    alert("Test");
}

if (x > y) {
    wait(z);
    testFunction();
}

Thanks!

Shawn J. Molloy
  • 2,457
  • 5
  • 41
  • 59
Abishek Roka
  • 75
  • 1
  • 2
  • 3
  • Have you tried placing the part of source code into a setTimeout? `setTimeout(function(){ //this will run after 3 seconds}, 3000);` If you could be more clear with your question and say which section you want to wait or why it might be easier for someone to give you a solid answer. – NewToJS Oct 25 '17 at 21:23
  • @NewToJS is right! Also you can take a look to this similar question https://stackoverflow.com/questions/14226803/wait-5-seconds-before-executing-next-line?rq=1 – lmoglia Mar 31 '21 at 19:55

3 Answers3

10

Can now nicely be done with promises:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
  console.log('Taking a break...');
  await sleep(2000);
  console.log('Two second later');
}

demo();
IAmCoder
  • 3,179
  • 2
  • 27
  • 49
6

Please try using the setTimeout function:

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

From this link:

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

So for your specific use case:

var timeToWait = 3000; // in miliseconds.
function testFunction() {
    alert("Test");
 }

 if (x > y) {
      setTimeout(function(){ testFunction(); }, timeToWait);
  }

Hope that helps.

Shawn J. Molloy
  • 2,457
  • 5
  • 41
  • 59
0

You have to put your code in the callback function you supply to setTimeout:

function stateChange(newState) {
    setTimeout(function () {
        if (newState == -1) {
            alert('VIDEO HAS STOPPED');
        }
    }, 5000);
}

From this question: Javascript - Wait 5 seconds before executing next line

prgrm
  • 3,734
  • 14
  • 40
  • 80