Search code examples
javascriptwait

i am trying to set a timeout between parts of my code but the syntax ignores the pause


alert ("hi")
alert("i will generate a random number on the screen and then  seconts tell you it and write it on the screen")
function e() {Math.Random()}
var number45654=Math.Random()
document.write (number45654)
function exec() {
    for(var i=0;i<5;i++) {
        setTimeout(function() {
            console.log(new Date());   //It's you code
        },(i+i+1)*1000);
    }
}
alert(number45654)
function exec() {
    for(var i=0;i<5;i++) {
        setTimeout(function() {
            console.log(new Date());   //It's you code
        },(i+i+1)*1000);
    }
}

i think it might be that that document.write or document.open() ignores timeouts but im not sure


Solution

  • It seems what you are trying to do is:

    // Function declarations should generaly come first
    function exec() {
        for(var i=0;i<5;i++) {
            setTimeout(function() {
                console.log(new Date());
            }, (i+i+1)*1000);
        }
    }
    
    alert("hi etc.")
    
    // Note that it is Math.random, not Math.Random
    var num = Math.random()
    document.write(num)
    alert(num)
    
    // Note that you should call the function, not re-declare it
    exec()