Question

hi everyone I am new to Javascript and would like to know how would I refresh an if else statement in javascript every 5 seconds, i have looked and cannot get anything to work thanks in advance.

<script type="text/javascript">

                if(total == randnum) {
                    document.write('Correct');
                } else {
                    document.write('Incorrect');
                }

 </script>
Was it helpful?

Solution

Do you need to write out the document or can you display the text in some element like a div?

If so then you can try something similar to what 'chopper' suggested:

Assuming you have a div in your page with the id "myDiv"

<div id="myDiv"></div>

Then use this to write out your text:

var myDiv = document.getElementById("myDiv");
setInterval(function () {
    if(total == randnum) {
        myDiv.innerHTML = "Correct";
    } else {
        myDiv.innerHTML = "Incorrect";
    }
}, 5000);

OTHER TIPS

Wrap the code you want to repeat inside a function an use setInterval() (click for documentation with examples) for repeating it.

myFunction() {
    //...
    // Your code
    //...
} 

setInterval(myFunction, 5000);

And if you want it to start immediately and then repeat:

myFunction();
setInterval(myFunction, 5000);

setInterval will execute a given function periodically, for example like this:

setInterval( function() {
    if(total == randnum) {
        $('#result').append('Correct<br/>');
    } else {
        $('#result').append('Incorrect<br/>');
    }
}, 5000);

Where

Of course you will have to define total and randnum.

See this jsFiddle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top