Search code examples
javascriptalertcountdown

Show JS Alert after 5 seconds


I am trying to show a JS alert after 5 seconds. Right now I have this code:

<script>
function init() {
    var count=5;
    var counter=setInterval(timer,1000);
        function timer(){
            count=count-1;
            if(count==0){
                alert("This is an alert")
                window.location = "http://www.example.com";      
                return;
            } 
        }
    }
    window.onload = init;
</script>

The problem is that it's not working right. There is some kind of little error I can't see in the code.


Solution

  • Why are you using setInterval and maintaining a count variable to deduce when five seconds have passed?

    Your code could be simplified using setTimeout. For example:

    window.onload = setTimeout(function(){
        alert('This is an alert');
        window.location = 'http://www.example.com';
    }, 5000);