currently, I'm redirecting users after x seconds to another page, but what I want to do is, redirect users after y seconds and the timer will start only after user click a link on my page, currently the timer starts only after the user visit my page.
Here is the code I found doing google search -
<head>
<script>
function js_wait()
{
setTimeout (js_go(), 3000); // 3000 ms = 3 secs
}
function js_go()
{
window.location = "mynexpage.php";
}
</script>
</head>
<body>
My link
</body>
The body shows a link
On click, it calls the javascript function "js_wait"
js_wait starts a timer for x seconds, then calls js_go
js_go redirects to the page.
I was able to make it redirect onclick but it redirects immediately after clicking the link, but I want it to wait y seconds before redirecting.
Dont activate the method instead just pass the function signature like this:
<head>
<script>
function js_wait()
{
setTimeout (js_go, 3000); // 3000 ms = 3 secs
}
function js_go()
{
window.location = "mynexpage.php";
}
</script>
</head>
<body>
My link
</body>
Remove () from setTimeout function parameter.
setTimeout (js_go, 3000); // 3000 ms = 3 secs
If you have it there, it means you pass the result of the function call rather then the function reference.
As background information, setTimeout can be used in two different ways: either you pass it a function reference, like what you have done, or you pass a string, which will be evaluated by the time setTimeout fires. This means that if you want to pass some parameters to setTimeout, you'd either pass them as a string (like setTimeout('js_go("http://google.fi")', 3000)) or wrap them to a function, which is the preferred way (setTimeout(function() {js_go("http://google.fi")}, 3000)).
However, since you don't use parameters here, you should just pass the function reference like shown in the code block above.
Try this please much simpler: Working demo http://jsfiddle.net/FE4cT/
For redirect this is key: window.parent.location
Rest I hope it will fit your need :)
code
function js_wait() {
setTimeout(function() {
window.parent.location = "http://www.google.com";
}, 3000);
}
Sample
window.setTimeout(function() {
window.location.href = 'http://www.google.com';
}, 3000);
i.e. in your specific case:
window.setTimeout(function() {
window.location = 'mynexpage.php';
}, 3000);
Simply write as :
function js_wait_redirect() {
setTimeout(
function(){
window.location = "mynexpage.php";
}
, 3000); // 3000 ms = 3 secs
}
Related
how do i make the window.location.url update every 30 seconds to the next id found in the array. Right now i have it alerting hello every few seconds but want the url to change instead
const myIds=['1_aq4jiqb','1_4u0ocu4u'];
for (let i = 0; i < myIds.length; i++) {
window.location.href = 'https://yahoo.com' + myIds[i]+ '/embed/iframe?';
}
setInterval(function(){ alert("Hello"); }, 3000);
<html>
</html>
update to the next Id after 30 seconds?
It's not possible unless you control each of those sites that you're redirecting to.
When you do window.location.href =, an entirely new document is loaded, with (and with only) the JavaScript(s) that new document links to. Anything that happens in your code after a single window.location.href = runs will be effectively ignored, because your old JavaScript does not carry over to the newly-loaded page.
Unless you control each of the sites you're redirecting to, the only way to accomplish this (on your browser only) would be to inject JavaScript code of your own into every site with a userscript.
If I understand what your're asking, just put the code inside a function, and call that at the setInterval.
const myIds=['1_aq4jiqb','1_4u0ocu4u'];
function switchId() {
for (let i = 0; i < myIds.length; i++) {
window.location.href = 'https://yahoo.com' + myIds[i]+ '/embed/iframe?';
}
}
setInterval(function(){ switchId() }, 3000);
<html>
</html>
What i want to do is exactly what i mentioned in the question title. I have a form with a submit button. Is it possible using jQuery to redirect the user to a specific link page after 5 seconds starting count from the moment this user clicked the submit button?
You can use setTimeout and window.location
setTimeout(function(event) {
window.location.href = url
}, 5000);
The below code do exactly what you want:
$('#button').click(function() {
setTimeout(function() {
window.location.href = 'http://new-url';
}, 5000);
})
This sounds like a job for JavaScript's setTimeout functionality.
The first thing you'll need to do is prevent the form submitting immediately (default behaviour) with event.preventDefault() otherwise nothing will be executed.
Check out this example with comments, Should provide a bit more information for you;
<form method="post">
<input type="text" name="text-field" placeholder="Enter something" />
<button type="submit">Submit form</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('form').on('submit', function(event) { // pass an event argument so we can call preventDefault
event.preventDefault(); // call event.preventDefault to stop form submitting immediately
setTimeout(function() { // Set up a setTimeout operation
console.log('form submitted after timeout');
window.location.href = '/';
}, 5000); /// 5000 ms == 5s
});
});
You need to use setTimeout in order to achieve what you want to achieve. setTimeout is a function which takes two parameters:
a callback function
the timeout in milliseconds
Callback
A callback function is a function to be executed when a given event happens. In our case the event is that a given amount of time elapsed. This is how your callback could look like:
function redirect() {
window.location.href = 'http://www.google.com';
}
Timeout
The timeout is the second parameter of the function. It defines the amount of time to elapse before the callback is being called. In our case you want 5 seconds to wait before the callback is executed, so the timeout will be 5000 milliseconds.
Usage
setTimeout(function() {
window.location.href = 'http://www.google.com';
}, 5000);
or
function redirect() {
window.location.href = 'http://www.google.com';
}
setTimeout(redirect, 5000);
Either way it is elegant to wrap a function around the solution and call the function on the onclick.
Here is a script I wrote so i could refresh a div with content every 5 seconds but for some reason it doesnt work ... I wanted it to load it with the page then start the refresh I didn't want it to have to wait for the refresh to show up.
<script type="text/javascript">
function page_load(){
$('#contentforads').load('<?php print $actual_link ?>/ads.php').fadeIn("slow");
}
function refresh(){
page_load();
var auto_refresh = setInterval(page_load,5000);
}
</script>
page_load() doesn't return a function, therefore you should pass it by reference to the interval rather than executing it.
var auto_refresh = setInterval(page_load,5000);
Don't forget to execute refresh to begin the interval.
function page_load(){
$('#contentforads').load('<?php print $actual_link ?>/ads.php').fadeIn("slow");
}
function refresh(){
page_load();
var auto_refresh = setInterval(page_load,5000);
}
refresh();
Change:
setInterval(page_load(),5000);
to:
setInterval(page_load,5000);
I'd change your code to this:
var a = function page_load(){
$('#contentforads').append(new Date());
}
setInterval(a, 5000); //every 5 seconds
Heres why I recommend:
Less code xD
Functions take up memory as they are considered variables in JS so this is more optimized
Note: Working fiddle
Provided that I have the javascript code below.
var timeout = setTimeout(function(){
alert('this is executed after 5 seconds');
}, 5000);
localStorage.setItem('timeout_event', timeout);
I have checked the return value of the setTimeout function to be an id or something. If the user refreshes the page, how do I re-run the timeout event? Is it even possible?
Any help will do. Thank you in advance.
I have checked the return value of the setTimeout function to be an id or something.
Yes, it is a numeric id which you can pass to clearTimeout for cancelling a scheduled function run.
If the user refreshes the page, how do I re-run the timeout event?
Yes, when the page is unloaded all outstanding timeouts are aborted, so you'll need to restart the timeout on the new page.
Is it even possible?
Yes and no. You won't be able to run the function which you scheduled from the last page - all its context/scope would be lost - you need to create a new one, in the context of the new page.
But if you want to execute certain functionalities based on a timeout/interval across pages, you can do so by using DOM storage or similar. You would store the timestamp of the designated function run, and a flag whether it has already run. That way, you can check on following pages whether and when you need to re-schedule the function.
If you want your timeout function to be executed whenever the page is refreshed , you just add the function in window.onload
var timeout = setTimeout(function(){
alert('this is executed after 5 seconds');
}, 5000);
window.onload = timeout;
This works fine for me
If you want it to be executed for multiple times , then go for setInterval()
var timeout = setInterval(function(){
alert('this is executed for each second');
}, 1000);
window.onload = timeout;
It will be executed until you call clearInterval(timeout);
If you want multiple timeouts then you should do something like this
var timeout = setTimeout(function(){
alert('this is executed after 1 second');
}, 1000);
var timeout1 = setTimeout(function(){
alert('this is executed after 2 seconds');
}, 2000);
var timeout2 = setTimeout(function(){
alert('this is executed after 3 seconds');
}, 3000);
window.onload = timeout;timeout1;timeout2;
This is because setTimeout calculates the time as soon as the page is refreshed and this works fine for me
Thanks for the help guys.
I managed to find a way to solve the problem.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Testing</title>
<script type="text/javascript">
var timeout_time = 10;
var time_remaining = 0;
if(localStorage.getItem('timeout_time')==null){
run_timeout(timeout_time);
}
else{
run_timeout(localStorage.getItem('timeout_time'))
}
setInterval(function(){
time_remaining = localStorage.getItem('timeout_time');
if(time_remaining > 1 || time_remaining != null){
localStorage.setItem('timeout_time', time_remaining - 1);
}
}, 1000);
function run_timeout(time){
setTimeout(function(){
alert('executed on 10 seconds');
localStorage.removeItem('timeout_time');
}, time * 1000);
localStorage.setItem('timeout_time', time);
}
</script>
</head>
<body>
This is the test page.
</body>
</html>
I hope this can be useful for others.
Again, thank you all.
I was wondering if there is any possibility through which one can reset the timeout of an AJAX request through an 'external' control. For example, let's say I have the following:
jQuery.fn.worker = function worker() {
$.get('/home/GetData', function (data) {
// Manipulate retrieved data
});
setTimeout(worker, 30000);
};
Would it be possible to have, let's say, a button through which I could reset the worker's timeout?
Thank you in advance!
Assuming you make the timer available globally, you can use clearTimeout(timer).
var timer = setTimeout(worker, 30000); // create
clearTimeout(timer); // clear