Edit Javascript and affect timer on HTML page in runtime - javascript

I am trying to skip timer placed on an HTLM page. Javascript for the TIMER is below:
var t = 60;
var decr = 1;
var handle = null;
var e = null;
function startTimer() {
if(!e) e = document.getElementById("time");
e.innerHTML = t;
handle = setInterval(function() {
if(t == 0) {
clearInterval(handle);
var answer = confirm("Yes/No?")
if (answer){
alert("You Clicked Yes!")
window.location = "https://twitter.com/";
}
else{
alert("You Clicked No!")
}
}
else {
t -= decr;
e.innerHTML = t;
}
}, decr * 1000);
}
window.onload = startTimer;
What I want is to change the TIMER to 10 seconds as soon as the page gets loaded.
I tried to enter the following code in browser location bar:
javascript:document.getElementById('time').innerHTML = "10";
But I'm not getting into it. What'll be the proper way to do it?

Open the console (development tools). If you are using chrome, press F12, then press console and insert the command
document.getElementById('time').innerHTML = "10";
or
document.getElementById('time').value = "10";
and then press enter.

Related

Why does my Code is not reloading by the time Given in Text field

window.onload = function() {
onPageLoad();
}
var reftime;
function refreshPage(){
var refreshtime = document.getElementById("r_time").value;
//var reftime;
reftime = setInterval(function() {
window.location.reload(true);
}, refreshtime*60000);
}
Above code is Js for reloading page.
<input id='r_time' type='text' name='r_time' value= ''/>
<input id='r_btn' type='button' value='Apply' style="font-size:12px;font-family:Helvetica;" onclick='refreshPage();'/>
This is my code it for reload my page it is reloading once when i gave time interval in minutes.But after once reloaded it is not reloading again.
The problem is that after reloading the window with window.location.reload(true) all your javascipt variables and intervals are gone.
So as soon as you reloaded the page for the first time no interval is running that will reload the page another time.
To get around this issue you have a few possibilities:
Don't reload the whole page. Just reload part of the page that changes.
This could be done with an asynchronous AJAX call retrieving the content to display from a server
Check out this solution to learn how to keep variables after reloading a html page.
After the reload you can then check in the window.onload function if you should start another inverval after some specified time.
For exaple if you want your page to reload itself after 1 minute, You can try just writing location.reload(0) in your onPageLoad() function like this:
window.onload = function() {
setTimeout(onPageLoad, 60000);
}
function onPageLoad() {
location.reload(0);
}
That should make your page reload after 1 minute(example).
Upon refresh, you'll start over again and the values of variables set will be gone. You can save the value using localStorage. Also, using setInterval in this case is unnecessary, you must use setTimeout
var reftime;
var input = document.getElementById("r_time");
window.onload = function() {
reftime = localStorage.getItem('time');
if (reftime) {
input.value = reftime;
refreshPage();
}
}
function refreshPage(){
var time = input.value || reftime;
localStorage.setItem('time', time);
setTimeout(function() {
window.location.reload(true);
}, time);
}
window.onload = function () {
onPageLoad();
}
var reftime;
function refreshPage() {
var refreshtime = document.getElementById("r_time").value;
// var reftime;
reftime = setInterval(function () {
location.reload(true);
}, refreshtime * 60000);
}
See if that Works.
For this code I am using cookies to save the value every time the website refreshes.
const _ = {
cookie_class: class cookies {
constructor() {
}
setCookie(cookie_name, cookie_value, expire_in_days) {
var d = new Date();
d.setTime(d.getTime() + (expire_in_days * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cookie_name + "=" + cookie_value + ";" + expires + ";path=/";
}
getCookie(cookie_name) {
var name = cookie_name + "=";
var ca = document.cookie.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 "";
}
exists(cookie) {
var user = this.getCookie(cookie);
if (user != "") {
return true;
} else {
return false;
}
}
}
}
const cookies = new _.cookie_class();
let interval;
const refresh = () => {
location.reload();
}
let cookie_name = "refresh_interval";
window.onload = () => {
if (cookies.exists(cookie_name)) {
interval = setInterval(refresh, parseInt(cookies.getCookie(cookie_name)));
}
}
const update = () => {
let value = document.getElementById('input').value;
if (!isNaN(parseInt(value))) {
cookies.setCookie(cookie_name, parseInt(value), 365);
clearInterval(interval);
interval = setInterval(refresh, parseInt(value));
} else {
// Handle is however you would Like:
// The input is not a Number
}
};
// Listeners
document.getElementById('apply-btn').addEventListener('click', (event) => {
event.preventDefault();
update();
});
Tell me if it works for you!

My tic tac toe game (jquery) is not working properly. Lost Part is not working properly

The 'Win' and 'Draw' parts are showing up on time, but the 'Lost' part doesn't show the message 'you lost'until I click on an empty cell once again. Please check out my code and help me find any errors.
Below is my code:
Marked is a class that changes the opacity of the clicked cell.
1,2,3...are the id's of respective cells in the table(html).
I tried delay() too instead of setTimeout(), but it didn't work as well.
$(document).ready(function() {
var timer;
var x = 0;
$("td").click(function() {
if($(this).text()=='') {
$(this).text("0").addClass("marked");
x = 1;
}
}).click(function() {
if(x==1) {
timer = setTimeout(function() {
var choose = $("td").not(".marked");
var random = choose[Math.floor(Math.random()*choose.length)];
$(random).text("X").addClass("marked");
},1000);
x=0;
showResult();
}
});
function showResult() {
var one = $("#1").text();
var two = $("#2").text();
var three = $("#3").text();
var four = $("#4").text();
var five = $("#5").text();
var six = $("#6").text();
var seven = $("#7").text();
var eight = $("#8").text();
var nine = $("#9").text();
if(one==two && two==three)
result(one)
else if (four==five && five==six)
result(four)
else if(seven==eight && eight==nine)
result(seven)
else if (one==four && four==seven)
result(one)
else if (two==five && five==eight)
result(two)
else if (three==six && six==nine)
result(three)
else if (one==five && five==nine)
result(one)
else if(three==five && five==seven)
result(three);
else {
var z = $("td").not(".marked");
if(z.length == 0) {
$("p").text("Draw!");
$("td").removeClass("marked");
$("td").text("");
$("#demo1").append('<img src="https://media.tenor.com/images/54c63f726505bfdb455eb4c29e626ad8/tenor.gif">');
clearTimeout(timer);
}
}
}
function result(y) {
var result = y;
if(result=="X"){
clearTimeout(timer);
$("p").text("You Lost!");
$("td").removeClass("marked");
$("td").text("");
$("#demo1").append('<img src="https://media.tenor.com/images/08902a85a6107684f8614846f4a54218/tenor.gif">');
}
if(result=="0") {
$("td").text("");
$("p").text("You Won!");
$("#demo1").append('<img src="https://i.gifer.com/4OuC.gif">');
$("td").removeClass("marked");
clearTimeout(timer);
}
}
});
You are calling showResult immeadiately when the user clicked, so it cant't recognize the X put into the table one second later.
Just do:
$("td").click(function() {
[...]
}).click(function() {
if (x == 1) {
timer = setTimeout(function() {
var choose = $("td").not(".marked");
var random = choose[Math.floor(Math.random() * choose.length)];
$(random).text("X").addClass("marked");
/******** ADD ANOTHER CHECK HERE ********/
showResult();
}, 1000);
x = 0;
showResult();
}
});
It might also be a good idea to add a return to showResult that returns false when a result was achieved. This way you could do something like
x = 0;
if (showResult()) {
timer = setTimeout(function() {
[...]
}
}
And the user can't get a loose message right after a win message.
Also: Why do you need the 2 click listeners? You can just use the if statement in the top one and then you don't need the (x == 1)

Reset animation to original position using javascript

using the following script i was able to move my picture right when clicked:
<script>
var myTimer = null;
function move(){
document.getElementById("fish").style.left =
parseInt(document.getElementById("fish").style.left)+1+'px';
}
window.onload=function(){
document.getElementById("fish").onclick=function(){
if(myTimer == null){
myTimer = setInterval("move();", 10);
}else{
clearInterval(myTimer);
myTimer = null;
}
}
}
</script>
I am having some trouble reseting the picture to original location without using jQuery.
If anyone can help that would be much appreciated.
If you capture the original position ahead of time you can reset later to the captured value:
var originalPosition = document.getElementById("fish").style.left;
function resetPosition() {
document.getElementById("fish").style.left = originalPosition;
}
Use external JavaScript. Some code to look at:
var pre = onload, E, doc, bod;// previous onload
onload = function(){
if(pre)pre();
doc = document; bod = doc.body;
E = function(id){
return doc.getElementById(id);
}
var fish = E('fish'), timer;
fish.onclick = function(){
if(!timer){
timer = setInterval(function(){
fish.style.left = parseInt(fish.style.left)+1+'px';
}, 10);
}
else{
clearInterval(timer); timer = false;
fish.style.left = '0'; // change '0' to what your CSS `left:`value is
}
}// end load
This should work fine,
var myTimer = null;
var startX = 0;
function move(){
document.getElementById("fish").style.left =
parseInt(document.getElementById("fish").style.left)+1+'px';
}
window.onload=function(){
document.getElementById("fish").onclick=function(){
if(myTimer == null){
startX = document.getElementById("fish").style.left;
myTimer = setInterval("move();", 10);
}else{
clearInterval(myTimer);
myTimer = null;
document.getElementById("fish").style.left = startX + "px";
}
}
}

Stopping a function from running

I have 3 sequential divs to display on a page, the page loads showing div 1, by going onto the 2nd it starts a timer, when that timer runs out it goes back to the first div. Navigating through to the next div should start the timer again. The timer function works OK on the first page but on the second page when it is called it is already running from the previous div and therefore ticks the time down twice as fast, and on the last div 3 times.
How can I get it to stop the currently running function then restart it?
Thanks,
$scope.timeLeft = 0;
var timeoutRunner = function (timerLength) {
$scope.timeLeft = timerLength;
var run = function () {
if ($scope.timeLeft >= 1) {
console.log($scope.timeLeft);
$scope.timeLeft--
$timeout(run, 1000);
} else if ($scope.timeLeft == 0){
$scope.endTransaction();
}
}
run();
}
timeoutRunner(5);
You need to add some logic that calls $timeout.cancel(timeoutRunner);.
Not sure where you want to cancel your timeout exactly (view change? when you end the transaction?) But here is how you would do it:
$scope.timeLeft = 0;
var timeoutPromise = false;
var timeoutRunner = function (timerLength) {
$scope.timeLeft = timerLength;
var run = function () {
if ($scope.timeLeft >= 1) {
console.log($scope.timeLeft);
$scope.timeLeft--
timeoutPromise = $timeout(run, 1000);
} else if ($scope.timeLeft == 0){
$scope.endTransaction();
$timeout.cancel(timeoutPromise);
}
}
run();
}
timeoutRunner(5);
Each time I called the function it created a new instance of it and I was unable to stop it on demand so I found a way to say which instance I want running:
$scope.timeLeft = 0;
var instanceRunning = 0;
var timeoutRunner = function (timerLength, instance) {
$scope.timeLeft = timerLength;
instanceRunning = instance;
var run = function () {
if (instanceRunning == instance){
if ($scope.timeLeft < 7 && $scope.timeLeft > 0){
$('#timer-container').show();
} else {
$('#timer-container').hide();
}
if ($scope.timeLeft >= 1) {
console.log($scope.timeLeft);
$scope.timeLeft--
$timeout(run, 1000);
} else if ($scope.timeLeft == 0){
$scope.endTransaction();
}
}
}
run();
}
timeoutRunner(20, 1);
timeoutRunner(20, 2);
timeoutRunner(20, 3);

Stop countdown on click

I want my countdown to stop on the click of a submit button, i searched in some pages,
but I didn't found anything.
Here is the code i want to stop on click
function countDown (count) {
if (count > 0) {
var d = document.getElementById("countDiv");
d.innerHTML = count;
setTimeout (function() { countDown(count-1); }, 1000);
document.getElementById('tiempo').value = count;
}
else
document.location = "timeover.php";
}
document.getElementById("palabra").focus();
countDown(5);
</script>
You have to save reference to timeout (actually return value of timeout will be number) and use it to cancel timeout.
var timeout = window.setTimeout(function () {
// do something
}, 1000);
// clear timeout
window.clearTimeout(timeout);
You probably got the idea. By the way, you should probably look at setInterval method since it would be better in this situation. Interval will "tick" as long until you cancel it.
Try something like this:
var stopped = false;
function countDown (count) {
if (count > 0) {
var d = document.getElementById("countDiv");
d.innerHTML = count;
document.getElementById('tiempo').value = count;
if (!stopped) {
setTimeout (function() { countDown(count-1); }, 1000);
}
}
else
document.location = "timeover.php";
}
document.getElementById("palabra").focus();
document.getElementById("mySubmitId").onclick = function () {
stopped = true;
};
countDown(5);

Categories

Resources