Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout function hangs my browser?

I an showing times using java script.

function showTime()
{
    setTimeout("showTime()", 500);      
    var now = new Date();
    var f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
    if (document.getElementById('foobar') == null)
    {
        showTime();
    }
    document.getElementById('foobar').innerHTML = f_date;

}

function strMonth(m)
{ ............ }

function timeFormat(curr_hour, curr_min)
{--------------}

showTime();

My Browser get sucked, or infinitely hanged. What should be the reason for that?

There is no showClock() only showTime().. Typo Mistake

like image 892
user12345 Avatar asked Mar 20 '26 20:03

user12345


2 Answers

use setInterval for this. Repetition is exactly what an interval is for (as opposed to a timeout).

Example:

//an edited showTime function for example
var showTime = function(){
    var now = new Date();
    document.getElementById('foobar').innerHTML = 
      now.toDateString()+" "+now.toTimeString();

};

//The interval
var myInterval = window.setInterval(showTime, 500);

Additionally: when you're done and want to stop the interval, use

window.clearInterval(myInterval);

Note per Pointy and the Mozilla docs setInterval can have issues.

Find out more here under the "Dangerous usage" section: https://developer.mozilla.org/en/window.setInterval

Edit: It appears your code has errors in one of the functions you did not post and that is causing your hangup. I've edited my example code to just demonstrate usage of an interval updating a time without any particular format and you can see that here at: http://jsfiddle.net/JVb2K/

like image 117
Jason Benson Avatar answered Mar 22 '26 08:03

Jason Benson


This should work:

function showTime() {    
    var now = new Date(),
        foo = document.getElementById('foobar');

    if ( foo != null ) {
        foo.innerHTML = now.getDate() + ' ' + strMonth( now.getMonth() ) + 
                ' ' + now.getFullYear() + ' / ' + 
                timeFormat( now.getHours(), now.getMinutes() ); 
        setTimeout(showTime, 500);
    }
}

showTime();

So, only if there is a foobar element on the page, you set its contents and do the timeout.

like image 40
Šime Vidas Avatar answered Mar 22 '26 09:03

Šime Vidas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!