This code in chrome happens in order but in safari It happens in the same and don't show the animation how can I fix it?(show the same in the safari)
window.onload = function() {
$(window).on("click", ".small1", function() {
me = this;
setTimeout(function() {
$(me).addClass("big");
}, 1);
window.open("http://google.com", "_self");
});
setTimeout takes Milliseconds as a parameter and not Seconds read here , the section about setTimeout
setTimeout() : Calls a function or evaluates an expression after a specified number of milliseconds
... Additionally , if you wish the window.open(.. to happen after the timeout finishes, you need to put it as well inside the setTimeout.
Please note that the timeout is only good for the function inside the setTimeout. Anything after the setTimeout statement executes asynchronously, so you'll have the window.open execute before the function inside setTimeout even started / finishes work.
So for instance ... the below should set the timeout to 1 second and also change the class and open the window after timeout expires.
window.onload = function() {
$(window).on("click", ".small1", function() {
me = this;
$(me).addClass("big"); // First gets big, considering that the css has the desired effect in Safari.
setTimeout(function() {
window.open("http://google.com", "_self"); // Executes now after timeout finishes.
}, 1000); // Timeout of one second.
});
Sample snippet below :
$(".small").on("click", function() {
me = this;
$(me).addClass("big");
setTimeout(function(){
window.open("http://google.com", "_self");},1000);
});
.big {
font-size: 150%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="small">myLink</div>
Related
in this code i want to when div with .ch1 class changed background to answer_box_small_orange.png other bottom js lines code don't run and no ajax request sends until 3 seconds and i used
window.setTimeout(function () {}, 3000)
but it doesnt work correctly
here first of all i request and get data and it is ok
$.ajax({
type:'post',
url:'http://207.154.251.233:8039/app.php/question/get',
data:JSON.stringify({apikey:'jwebdpqodp9fgkwjebfkdpqihdqlwkndqp'}),
success:(function (response) {
var x = response;
$("#question").text(x.result.question);
$(".op1").text(x.result.options["1"]);
})
});
i inserted ajax code and some other codes in function because i want to run it every 60 seconds
function myInterval () {
$(".ch1").css('background-image','url(image/answer_box_small.png)');
var clock;
$(document).ready(function() {
clock = new FlipClock($('.clock'), 60, {
clockFace: 'Counter',
autoStart: true,
countdown: true,
callbacks: {
stop: function() {
$('#loading').fadeIn('5000');
$.ajax({
type:'post',
url:'http://79.175.166.98/',
data:JSON.stringify({apikey:'jwebdpqodp9fgkwjebfkdpqihdqlwkndqp'}),
success:(function (response) {
$('#loading').fadeOut('slow');
var x = response;
$("#question").text(x.result.question);
$(".op1").text(x.result.options["1"]);
var answer = x.result.answer;
if(answer == 1){
$(".ch1").css('background-image','url(image/answer_box_small_orange.png)');
}
window.setTimeout(function () {}, 3000);
})
});
}
}
});
});
}
myInterval();
window.setInterval(function(){
myInterval();
}, 60000);
Based on what you told me, my interpretation is that you have a setTimeout() function and a setInterval() function. The setTimeout() runs at the beginning and will wait for 3 seconds. Then call an ajax function to create new requests every 6 seconds. Your problem seems to be that your first setTimeout() is re-run after you create your first AJAX request, but you want it to stop.
Taken from W3
setTimeout Return Value: A Number, representing the ID value of the timer that is set. Use this value with the clearTimeout() method to cancel the timer.
Knowing this, we can essentially cancel a setTimout() function. In your case, the first setTimeout().
Consider this,
var firstIntervalID = setTimeout(function() {
$.ajax() {
// First AJAX ran after three seconds.
}
}, 3000);
clearTimeout(firstIntervalID);
// Your code resumes to set an interval every 60 seconds without having to worry about the three seconds set before
myInterval();
var secondIntervalID = setInterval(function(){
myInterval();
}, 60000);
Essentially, you cancel the setTimeout() when you don't need it anymore. Your application for it can be different than what I wrote, but the main idea is the same. Cancel/Clear the setTimeout() with the ID that is returned on setTimeout() with clearTimeout().
My objective is to keep a user in a view as long as he/she keeps clicking a button within a certain lapse.
I'm using Rails and was exploring a solution via an embedded JS in the pertinent view.
So far I'm able to set a time after which the user will be redirected to root path with the following script:
var delayedRedirect = function (){
window.location = "/";
}
var delay = 10000;
$(document).ready(function() {
setTimeout('delayedRedirect()', delay);
});
I've been trying to write a function that resets the value of 'delay'or that calls the setTimeoutFunction again.
$('#btn-persist').click(function() {
delay = 3000;
// or calling again setTimeout('delayedRedirect()', delay);
});
But I noticed that changing the variable won't affect the setTimeout function that has already been called.
I've also tried to use the clearTimeout function as below without success
var delayedRedirect = function (){
window.location = "/persists";
}
var delay = 3000;
var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);
}
var stopRedirect = function (){
clearTimeout(triggerRedirect);
}
$(document).ready(function() {
triggerRedirect();
$('#btn-persist').click(function() {
stopRedirect();
});
});
I wonder why this may not be working and if there's any other way to stop the execution of the setTimeout function that has already been called so I can call it again to effectively reset the time to the original value of 'delay'.
At the same time, I don't want to stop any other JS functions that are running in parallel.
Do you see a better solution to achieve this?
The main problem why clearTimeout is not working. because you are clearing a anonymous function instead of a setTimeout variable
change this
var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);
}
to this
var triggerRedirect = setTimeout('delayedRedirect()', delay);
Edit:
also change this (if you want to restart the inactive redirect trigger)
$('#btn-persist').click(function() {
stopRedirect();
});
to this
$('#btn-persist').click(function() {
stopRedirect();
triggerRedirect();
});
I have an unusual problem. I'm using the following script to check for internet connection using navigator.onLine. If there is internet connection, the page will be refreshed every 15 seconds. If there isn't any internet connection, the page will use innerHTML to display a message.
<script type="text/javascript">
setInterval(function () {
if (navigator.onLine) {
var myInterval = setInterval(function(){window.location.href = "Tracker.html";},15000);
} else {
clearInterval(myInterval);
var changeMe = document.getElementById("change");
change.innerHTML = "<big><font face='Arial' color='#ffffff' size='2'><center>OFFLINE</big><br>No internet connection</font></center>";
}
}, 250);
</script>
My problem is, once there is no internet connection, the message will be displayed, BUT the page would still be refreshed one last time. I'm trying to avoid this, by using clearInterval(myInterval); in the else part of the code, however it won't work.
Any suggestions?
To refresh the page at 15 second intervals (provided that a connection is present), use:
function refresh() {
if(navigator.onLine)
window.location.href = "Tracker.html";
else{
var changeMe = document.getElementById("change");
change.innerHTML = "<big><font face='Arial' color='#ffffff' size='2'><center>OFFLINE</big><br>No internet connection</font></center>";
setTimeout(refresh, 250);
}
}
setTimeout(refresh, 15000);
At the end of 15 seconds, this checks whether a connection is present. If there is, it refreshes the page. If there isn't, it proceeds to check every 250 milliseconds afterwards until the user is reconnected, at which point it refreshes the page.
The net result is that the script refreshes the page as soon as possible after a minimum of 15 seconds have elapsed.
Here is a demonstration: http://jsfiddle.net/JGEt9/show
Whenever the outer interval callback is executed, a new myInterval variable is created and the previous one is lost (it goes out of scope because the callback terminates).
You have to persist the value of the variable between function calls by declaring it outside of the function. You also have to make sure that you are not creating another timeout if one is already running.
var timeout = null;
setInterval(function () {
if (navigator.onLine) {
if (timeout === null) {
timeout = setInterval(function(){window.location.href = "Tracker.html";},15000);
}
} else {
clearTimeout(timeout);
timeout = null;
// ...
}
}, 250);
You need to declare myInterval outside of the if statement. You should only need the refresh code once too. Something like this:
var myInterval = setTimeout(function(){window.location.href = "Tracker.html";},15000);
setInterval(function () {
if (!navigator.onLine) {
clearTimeout(myInterval);
var changeMe = document.getElementById("change");
changeMe.innerHTML = "<big><font face='Arial' color='#ffffff' size='2'><center>OFFLINE</big><br>No internet connection</font></center>";
}
}, 250);
Here you set the refresh interval and continually check to see if the browser is offline, and if it is, you remove the timer and do your cleanup code. I also changed the refresh code to use setTimeout instead of interval because it only happens once.
Another issue is you create changeMe but then try to use change. change doesn't exist. I fixed that in my example as well.
Note: This will not resume refreshing once connection is regained. See Felix Kling's answer.
I am trying to remove a DOM element after a delay. I also wish to cancel this removal with a user click (if they click before the timer expires. This is what I have:
<div class="delete">Delete me!</div>
Obviously, I am only showing the relevant source.
$("div.delete").click(function() {
var element = $(this),
timeout = element.attr('data-timeout');
if (timeout) {
clearTimeout(timeout);
element.removeAttr('data-timeout');
element.text("Delete me!");
} else {
timeout = setTimeout(function() {
element.remove();
alert('Sniff, too late!');
}, 2000);
element.attr('data-timeout', timeout);
element.text("Save me!");
}
});
This works! My questions
Is there a better way? My first failed try had mutiple handlers.
Why doesn't it work in Javascript 1.7?
http://jsfiddle.net/zhon/H8a9J/
It doesn't work with JavaScript 1.7 because the browser you are using doesn't support it and/or or the way how it's embedded. Your fiddle works fine with Firefox.
http://en.wikipedia.org/wiki/Comparison_of_layout_engines_%28ECMAScript%29
You need to define timeout outside of your handler.
var timeout;
$("div.delete").click(function() {
var element = $(this);
if (timeout) {
clearTimeout(timeout);
timeout = undefined;
element.text("Delete me!");
} else {
timeout = setTimeout(function() {
element.remove();
alert('Sniff, too late!');
}, 2000);
element.text("Save me!");
}
});
I'd recommend enclosing the code to add handlers within some other function to avoid muddying the global namespace with timeout ids.
Make timeout a global, and clear it on the user click.
clearTimeout(timeout);
I am trying to get onbeforeunload to work with a set timer of sorts but I can't seem to get it to fire up when the return is in place. I am hoping it would work with a timer but for some reason the timer isn't working. Here is the code I am working and thank you for your help in looking at it much appreciated.
var validNavigation = false;
function wireUpEvents() {
var leave_message = 'Leaving the page';
jQuery(
function goodbye() {
jQuery(window).bind('onbeforeunload', function() {
setTimeout(function() {
setTimeout(function() {
jQuery(document.body).css('background-color', 'red');
}, 10000);
},1);
return leave_message;
});
});
function leave() {
if(!validNavigation) {
killSession();
}
}
//set event handlers for the onbeforeunload and onunloan events
window.onbeforeunload = goodbye;
window.onunload=leave;
}
// Wire up the events as soon as the DOM tree is ready
jQuery(document).ready(function () {
wireUpEvents();
});
onBeforeUnload doesn't work with setTimeout. After onBeforeUnload executes, onUnload will be triggered and the page will change. This happens before the setTimeout callback is called.
#Jonh Kurlak is right, onbeforeunload doenst work with timeout to protect the browser user from being scammed.
But there is something you can do!!!
for(var i = 0; i < 1000; i++){
console.log(i);
}
You can make this for loop printing to console to delay the unload of the page, the higher the number of iterations it as to loop through the longer it waits.