开发者

what is setTimeOut() function in javascript?

Can i ask what the function of setTimeOut method in javascript?As below:

function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds()开发者_高级运维;
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}


Not sure you what you want.

setTimeout is a method of the global window object. It executes the given function (or evaluates the given string) after the time given as second parameter passed.

Read more about setTimeout.


setTimeout() just schedules (sets a timer for) a function to execute at a later time, 500ms in this case. In your specific code, it's updating the screen with the current time every half-second (it only schedules one call, 500ms from now...but that startTime call scheduled another).

Also...passing a string to it when you can avoid it is bad practice, for your example it should be:

t = setTimeout(startTime, 500);


It schedules your startTime function to start again half a second later (500 miliseconds), updating you clock.


setTimeOut sets a timer and executes the given code after that timer timed out. So using your code, if startTime is called once, it is repeated every half second.

Btw. I assume the delay of 500 ms is used te work around small deviations in the clock. You will want to update the value of the element every whole second. To do that, it is better to calculate the time until the next whole second and set that as a delay. This will give you a more accurate clock.


The setTimeout() method allows you to execute a piece of code after a certain amount of time has passed. You can think of the method as a way to set a timer to run JavaScript code at a certain time.

For example, the code below will print "Hello World" to the JavaScript console after 2 seconds have passed:

setTimeout(function(){
    console.log("Hello World");
}, 2000);

console.log("setTimeout() example...");

output:-

  • setTimeOut() example...
  • Hello World

OR


function greeting(){
  console.log("Hello World");
}

setTimeout(greeting, 2000);

If you omit the second parameter, then setTimeout() will immediately execute the passed function without waiting at all.

You can also pass additional parameters to the setTimeout() method.

function greeting(name, city){
  console.log(`Hello, my name is ${name}`);
  console.log(`I live in ${city}`);
}

setTimeout(greeting, 2000, "Milan", "Kathmandu");

    
                      
                                       
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜