JavaScript Doesn't do anythign when I click button - javascript

var timeout = false;
setTimeout(function(){
timeout = true;
}, 3000);
$("#waitForClick").on('click',function(){
if(!timeout)
alert("Please comment this website in comments of games.");
else
window.location = "step3.php";
});
What it should do is wait 3 seconds and alert them a message before redirecting to the next page.

Try putting the setTimeout inside of the on click function... I'm assuming you want to wait three seconds AFTER you click?

Try this, for some reason jsfiddle isn't letting me save anything at the moment.
$(document).ready(function() {
$('#waitForClick').on('click', function(){
setTimeout(function() {
alert("Please comment this website in comments of games.");
window.location = "step3.php";
}, 3000);
});
});

I try to put your code inside a document.ready... and it's works:
$(document).ready(function () {
var timeout = false;
setTimeout(function(){
timeout = true;
}, 3000);
$("#waitForClick").click(function(){
if(!timeout){
alert("Please comment this website in comments of games.");
}else{
window.location = "step3.php";
}
});
});
Your element was not loaded when you called.
Please do not forget to import jQuery!
(Sorry for my bad english)

Related

Prevent Javascript Page Reload

I am using this javascript to auto refresh a page every 30 seconds.
<script type="text/javascript">
window.setTimeout(function(){ document.location.reload(true); }, 30000);
</script>
I need to give users an option to disable this function at any time before the page is reloaded.
Note: this is for an admin panel, not a public website, and the requirement from the client is that the page auto refreshes, with an option to stop the refresh before it happens by clicking a button.
Is there any way to achieve this... That is.. disable the javascript before it executes?
clearTimeout() : Cancels a timeout previously established by calling setTimeout().
You're searching for clearTimeout() :
var refresh = window.setTimeout(function(){ document.location.reload(true); }, 30000);
$('body').on('click', '#my-button', function(){
clearTimeout(refresh);
})
Hope this helps.
Do it this way:
var myVar;
function myFunction() {
myVar = window.setTimeout(function(){ document.location.reload(true); }, 30000);
}
function myStopFunction() {
clearTimeout(myVar);
}
You just have to call the myStopFunction in order to stop the auto reload.
Do the following:
reload = window.setTimeout(function(){ document.location.reload(true); }, 30000);
Or, if using jQuery,
$("#non-reload-button").click(function(){
clearTimeOut(reload)
});
Below is code that will continue to execute every 500ms until you click the button to stop it. Just replace the 500 with the time you want and replace the console.log with what ever operation you wish to run. Hope this helps!
let auto_refresh_active = true;
const refresh = () => {
window.setTimeout(e => {
console.log('Hey, I am running! Click the button to stop me!')
if(auto_refresh_active == true) refresh();
}, 500)
}
refresh();
document.querySelector('button').addEventListener('click', e => auto_refresh_active = false);
<button>stop running</button>

how to stop a Javascript function when the user switch tab or minimize the broswer

I'm creating a chat that need to retrieve messages from PHP using AJAX in intervals. The problem is that the users can open multiple tab of different chatroom, and that's going to take a a lot of resource from the server. So, how can I stop a function in the other tabs when the user switches page, then reactive it when they return to the tab. I'm new to coding so please keep the code as simple as possible (NO jQuery please.)
Here is an function test I was trying, but no luck:
function window_active(){
window.onfocus = function() {
test()
};
window.onblur = function() {
//stop the script OR change the setTimeout so the functon run less.
};
}
function test(){
alert('adadasdad');
setTimeout(function(){}, 10000);
}
Thanks in advance. (:
Update:
requestAnimationFrame() didnt work.
function loop() {
var div_id = document.getElementById('tester');
var msg = document.createTextNode("sadksadkjsahdjkasdjkahdjkas");
div_id.appendChild(msg);
setTimeout( function() {
requestAnimationFrame( function() {
loop();
} );
}, 1000 );
}
Update 2:
Counldn't find this answer anywhere, and then I got lucky and found this page with the help of ehynds answer about "document.hidden". Thanks ehynds! (:
function loop() {
//do stuff.
setTimeout( function() {
if(document.hasFocus()){
//"document.hasFocus()" return **true** only if your on the tab.
loop();
}
}, 1000);
window.onfocus = function() {
//reactivted the function.
loop();
};
}
Hopes this help someone looking for the answer. (:
HTML5 visibility API:
document.addEventListener('visibilitychange', function() {
document.hidden; // whether or not the tab is visible
});

Collect async calls and submit the last one

I try to create an image depend on an input field. The image created on the server, I get it by an async call, and it have to be generated after every keyup in the input field. If the user hit another key while the previous call isn't finished, this call have to be stucked. After the first call is finished, this stacked have to be called. The point, if the user hit a tons of keys while the first call is not finished, only the last one have to be called once.
I created a fiddle for it, where I simulated the async call with a settimeout function. I can't figure out, why it isn't working.
var isRequestInProgress = false;
var nextRequest = null;
var submit = function(content) {
console.log('isRequestInProgress: ' + isRequestInProgress); // It should be true in the second turn
if (isRequestInProgress === true) {
nextRequest = content;
return false;
}
isRequestInProgress = true;
setTimeout(function() {
isRequestInProgress = true;
if (nextRequest !== null) {
submit(nextRequest);
}
nextRequest = null;
isRequestInProgress = false;
}, 2000);
};
$('button').click(function() {
isRequestInProgress = false;
submit($(this).text());
});
The isRequestInProgress should be true, if I press a button after another, in 2 mins. But it false, and I don't know, why...
if you know why, or you have a better solution to solve this problem, I would glad to hear it!
Thanks in advance!
If i get it right:
var isRequestInProgress = false,
timeout;
var submit = function(content) {
if (isRequestInProgress === true) {
clearTimeout(timeout);
}
isRequestInProgress = true;
timeout = setTimeout(function() {
console.log('content: ' + content);
isRequestInProgress = false;
}, 2000);
};
$('button').click(function() {
submit($(this).text());
});
Use .abort() method of XMLHttpRequest object to stop an AJAX request.
Assuming you're using setTimeout, clear the timer using clearTimeout before submitting
http://jsfiddle.net/27gmpjj2/1/
If you're using Ajax, use abort(), as suggested by seva.rubbo
http://jsfiddle.net/27gmpjj2/2/
If you want to submit an ajax request only on the last button-press, then you can use the setTimeout approach. This will delay the request until we're sure the user has stopped pressing buttons.
http://jsfiddle.net/27gmpjj2/5/

Button to refresh page every second/minute etc?

I'm wanting a button that when clicked will refresh the current page after a specified amount of time.
I currently have:
<script type="text/javascript">
setTimeout(function reload(){
location = ''
},1000)
</script>
<button onclick="reload()">Reload</button>
However, that JUST reloads the page without even having to click the button. I'm wanting the button to execute the script, and also a button to STOP the page reload.
This should be really simple but I can't figure it out :(
******EDIT**********
I'd also like the script to run on an infinite loop after the button is clicked.
Your setTimeout is called on page load. You need to put it inside the reload() function:
function reload() {
setTimeout(function() {
window.location.reload();
}, 1000);
}
To make the timer run every x seconds and reload only a part of the page you would need to use setInterval and an AJAX request, something like this:
var timer;
function reload() {
timer = setInterval(function() {
$.post('foo.html', function(data) {
$('#bar').html(data);
});
}, 1000);
}
function clear() {
clearInterval(timer);
}
This should do the trick
<script type="text/javascript">
function reload(){
setTimeout(function(){location.reload()}, 3000);
}
</script>
<button onclick="reload()">Reload</button>
What you wrote is
window.setTimeout("location = ''"; ,1000);
You were saying execute this function after 1 second. You need to define the setTimeout inside the function. Also there is a built in method to reload the page. Call that instead of setting the location to a blank string.
function reload() {
setTimeout( function() {
window.location.reload(true);
},1000);
}
Now to cancel the timeout, you need to use clearTimeout(timeoutId); You get the timeoutId from the integer that the setTimeout returns when you call it.
var timer = null;
function reload() {
timer = window.setTimeout( function() {
window.location.reload(true);
},1000);
}
function cancelReload() {
if (timer) {
window.clearTimeout(timer);
}
timer = null;
}
AND you said you want it to keep running. That will require cookies or localstorage.
var timer = null;
function reload() {
localStorage.reload = true; //set localstorage so we know to fire it off again
timer = window.setTimeout( function() {
window.location.reload(true);
},1000);
}
function cancelReload() {
if (timer) {
window.clearTimeout(timer);
}
timer = null;
localStorage.removeItem("reload"); //remove the key in localstorage
}
if (localstorage.reload) { //check localstorage to see if key is set
reload();
}
You need to wrap the whole thing in another function and call that from the button click

click event delay and pre loader animation

I want to combine two techniques in page transition. first, when user click a link , the click event should be delayed about 200ms and displaying css animation (ex: fading), after that the new page will be loaded normally. Then, for visitors with slow internet connection, they will be presented with pre-loader right after the first animation. The problem is, it seems both techniques doesn't fit each others. Any advice guys?
PS: Actually I inspired by these guys website : http://rsq.com/
here's my code:
$body = $("body");
$(document).on({
ajaxStart: function () {
$body.addClass("loading"); //for slow connection, visitors with faster connection may not notice this...
},
ajaxStop: function () {
$body.removeClass("loading");
}
});
$('a').on("click", function () {
if ($(this).attr('href') != '#') {
var href = $(this).attr('href');
$('#wrapper').addClass('fade_animation'); //animation right before new page request
setTimeout(function () {
window.location = href
}, 200);
return false;
$.post($(this).attr('href'));
}
});
I think this is enough:
Instead of:
return false;
$.post($(this).attr('href'));
do this
$.post($(this).attr('href'));
return false;
So the $.post gets executed.
I think i found a solution , but don't know if it's a good way, but it works.
$('a').on("click", function(){
if($(this).attr('href') != '#')
{
var href = $(this).attr('href');
$('#wrapper, footer').addClass('fading animation');
setTimeout(function() {
// window.location = href
$.post(window.location = href) // this line works :)
}, 200);
return false;
// $.post($(this).attr('href'));
}
});

Categories