Greetings I wanted to implement a cookie timer on the site: A random visitor clicks a button, for example, a background color changes, the timer runs for 1 hour and after leaving the page, the user’s cookie stores how long it will remain until the next button click. Thanks in advance for your help! :)
Closed due to the fact that the essence of the issue is incomprehensible to the participants Mr. Black , cheops , aleksandr barakin , user194374, lexxl Aug 2 '16 at 7:41 .
Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .
|
1 answer
Here it is. I think you will understand.
var TIMEOUT = 15; // sec function showTime(t) { document.getElementById("time").innerHTML = (t != 0) ? t : ""; } function timer(t) { document.getElementById("btn").disabled = true; if (t == undefined) t = TIMEOUT; showTime(t); var interval = setInterval(function() { --t; showTime(t); if (t <= 0) { clearInterval(interval); document.getElementById("btn").disabled = false; } }, 1000); } function onClick() { document.cookie = "timeout=" + new Date(); timer(); } function getCookie(name) { var matches = document.cookie.match( new RegExp("(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)") ); return matches ? decodeURIComponent(matches[1]) : undefined; } function onLoad() { var prevStartTime = new Date(getCookie("timeout")); var delta = TIMEOUT - Math.round((new Date() - prevStartTime) / 1000); if (delta > 0) { timer(delta); } } <body onload="onLoad();"> <button id="btn" onclick="onClick();">Click me!</button> <br /> <span id="time"></span> </body> Read more about cookies here . It also stole the getCookie function.
- Thank you very much! Works! Can you tell me how to make an event after the timer ends, for example changing the background color in js? Thanks in advance :) - HolyDi
- The
timerfunction has anif (t <= 0)if, the body of thisifis executed after the timer has expired. There you can perform any actions, including changing the background with a command likedocument.body.style.background = "yellow". - user194374 - Yes, I already realized, I hurried with the question and forgot to specify, what if for a unique block with id? - HolyDi
document.getElementById("идентификатор").style.background = "yellow"- user194374
|
setTimeout()function. at the time of the start of the timer save the expected completion time. If the page is closed and dug up again, see the saved time — if it is more than the current one — calculate the remainder and setTimeout on it. - Mike