1

I have some trivial code like the following:

 var timer_ends = some_ts; var timer = setInterval(function() { time_diff = /* some calculation */ if ( time_diff <= 0 ) { clearInterval(timer) // Want to location.reload(true) here but it would recursively run return; } }, 1000); 

Once the timer hits 0 or below, I want to

  • clearInterval(timer)
  • I want to refresh the page

The problem is, if I refresh the page, the timer will just restart and we'll recursively keep refreshing. What is the best way to execute the location.reload(true) once and only once the first time time_diff hits 0. Also, if the user is coming to the page for the first time and it's already at 0 it shouldn't refresh.

9
  • 1
    Have you tried using cookies? Commented Nov 9, 2018 at 19:24
  • can also use localStorage if server is not involved in the timing or tracking Commented Nov 9, 2018 at 19:26
  • What is local storage? Commented Nov 9, 2018 at 19:30
  • @JermahlWhite plese see docs here Window localStorage Property Commented Nov 9, 2018 at 19:34
  • Why do you want to refresh at all? Commented Nov 9, 2018 at 19:34

2 Answers 2

1
 var timer_ends = some_ts; if (Boolean(localStorage.isEnteredBefore)) return; var timer = setInterval(function() { time_diff = /* some calculation */ if ( time_diff <= 0 ) { clearInterval(timer) // Want to location.reload(true) here but it would recursively run localStorage.isEnteredBefore = true; return; } }, 1000); 
Sign up to request clarification or add additional context in comments.

1 Comment

Assuming that you are at the function level.
1

The code for the cookies is from W3Schools. This should be what you want

function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i <ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } var timer_ends = some_ts; var timer = setInterval(function() { time_diff = /* some calculation */ if ( time_diff <= 0 ) { clearInterval(timer) if(getCookie('done')) return setCookie('done', true, 30) location.reload(true) //No need to return here because it's already reloading } }, 1000); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.