简体   繁体   中英

setInterval not working with content auto update

I'm trying to use this https://codepen.io/zeinab92/pen/xwWGWM

But It's not updating 'Hours, Minutes and Status' automatically without page reload.

How can I make it working so, times will automatically update and state text will also update based on the time condition whether it's Open or Closed.

I like the script except the auto update problem, I tried by create a new function,

setInterval(function() {
  $("#timeDiv").html(data);
}, 1000);

by disabling default

setInterval(checkTime, 1000);

or setTimeout instead of setInterval

But no luck.

After debugging, I found the problem with the code.

You have declared now as global variable outside checkTime function and when page loads now variable stores value of new Date ie the value of Date when page has been loaded. Hence the value of now is updated only once as global variable are executed only once.

Solution: Place the now variable inside checkTime so that each time it will have new value of Date whenever checkTime is called.

function checkTime(){
var now=new Date();

....
}

Hope this resolves the issue. ( JS Fiddle )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM