Unexpected token ILLEGAL when using setTimeout/Cleartimeout - javascript

This is what i want: Timeout when i hover out of a div, cancel if i hover on top of the div again.
The code works if i remove the cancelfunction. So showing and hiding the div works fine.
This is my code:
$(document).ready(function ()
{
var timeoutID;
function clearAlert()
{
window.clearTimeout(timeoutID);
}​
if ($('.txtVote').text() == "Avgi stemme")
{
$('#starInfo').hover(
function ()
{
clearAlert();
$('#CarDetailsButtons').css('right', '10px');
$('#voteStars').show();
},
function ()
{
console.log("hide iniated");
timeoutID = window.setTimeout(hideStars, 2000);
console.log("hide executed");
});
}
function hideStars()
{
console.log("hideStars ran");
$('#CarDetailsButtons').css('right', '45px');
$('#voteStars').hide();
}
});
And, this is my error:
Uncaught SyntaxError: Unexpected token ILLEGAL
which appears on the line right after window.clearTimeout(timeoutID);
Anyone able to see what I'm doing wrong? :)
EDIT: *WORKS*
So, it seems i had some kind of copy paste bug. I wrote the function clearAlert manually, just like it was before, and it works now.
Thanks for all the input!

try this:
var that = this;
that.timeoutID = null;
...
that.timeoutID = ...
OR
you have to declare var timeoutID = null; global. So you have the var in a gloabl context and not within the function-context of $(document).ready.
the best solution ist to write a little js-class with the timer in it. so you have no global conflicts an it works.
greetings!

I would suggest you to move your functions outside of doc ready like this:
function hideStars()
{
console.log("hideStars ran");
$('#CarDetailsButtons').css('right', '45px');
$('#voteStars').hide();
}
function clearAlert()
{
window.clearTimeout(timeoutID);
}​
$(document).ready(function ()
{
var timeoutID;
if ($('.txtVote').text() == "Avgi stemme")
{
$('#starInfo').hover(
function ()
{
clearAlert();
$('#CarDetailsButtons').css('right', '10px');
$('#voteStars').show();
},
function ()
{
console.log("hide iniated");
timeoutID = window.setTimeout(hideStars, 2000);
console.log("hide executed");
});
}
});

Related

Events fire but nothing happens?

I'm following this course on pluralsight about making web apps using .NET Core. The author uses jQuery 2.4.3 I think and I just picked the newest jQuery myself which 3.x.
So I write the code exactly like he does:
(function () {
var ele = $("#userName");
ele.text("Some Dude");
var main = $("#main");
main.on("mouseenter", function () {
main.css("background-color", "#888;");
});
main.on("mouseleave", function () {
main.css("background-color", "");
});
})();
And at first nothing happened when I moused over my div. It doesn't change color. Nothing much seems to register at all. So I went hunting an I found that this is how I should probably do it instead:
(function () {
var ele = $("#userName");
ele.text("Some Dude");
var main = $("#main");
main.on("mouseover", function () {
console.log("enter");
main.css("background-color", "#888;");
})
.on("mouseout", function () {
console.log("out");
main.css("background-color", "");
});
})();
And while the console prints out "enter" and "out", the background color of my div still doesn't change.
What did I miss about this?
Maybe remove ";" in main.css("background-color", "#888;")

Run function when other function is completed

Im looking for a way to run a function when the other function is ready.
This is the function:
$(".box").first().show(150, function showNext () {
$(this).next(".box").show(150, showNext);
});
So Im look for a way to run another function after that, for example:
alert("Done");
I've tried this but didn't work.
$(".box").first().show(150, function showNext () {
$(this).next(".box").show(150, showNext);
}, function () {
alert("Done");
});
What I want is, in words:
if(all .box is visble or if showNext is idle/completed){
alert("Done");
}
I appreciate any help! Thanks.
How about :
$(".box").first().show(150, function showNext () {
var next = $(this).next(".box");
if (next.length > 0) { // If a next sibling with class "box" was found
next.show(150, showNext);
} else { // No sibling found, end reached
alert("Done");
}
});

How to make this script pause on hover?

I'm new to jQuery and I need a bit of help. I'm using this jQuery script as a testimonial rotator and it works like a charm but I just need to make one small tweak. I need it to be able to pause on hover and then restart when the mouse leaves the div. How can I do this?
This is the script I'm using:
function fadeMyContent() {
$(".testimonial:first").fadeIn(1000).delay(3000).fadeOut(1000,
function() {
$(this).appendTo($(this).parent());
fadeMyContent();
});
}
fadeMyContent();
});
Here is a JSFiddle.
There is a plugin that will provide all the functionality you need and be more reliable called jQuery Cycle 2.
It provides a 'pause-on-hover' option when initialising it.
change the definition of fadeMyContent (also called as destroying function) on hovering on ul#testimonial-rotator and on hover-out change it to old definition again. I have used setTimeout in place of delay because delay is not cancellable.
$(document).ready(function () {
var fadeMyContent;
var t
fadeMyContent = function () {
$(".rotate:first").fadeIn(1000)
t = setTimeout(function () {
$(".rotate:first").fadeOut(1000,
function () {
$(this).appendTo($(this).parent());
fadeMyContent();
});
}, 3000)
}
var fadeMyContentDummy = function () {
$(".rotate:first").fadeOut(1000,
function () {
$(this).appendTo($(this).parent());
fadeMyContent()
});
}
fadeMyContent();
$('#testimonial-rotator').hover(function (e)
{
window.clearTimeout(t)
$('.rotate:first').clearQueue()
fadeMyContent = function () {
return false;
}
},
function (e)
{
fadeMyContent = function () {
$(".rotate:first").fadeIn(1000)
t = setTimeout(function () {
$(".rotate:first").fadeOut(1000,
function () {
$(this).appendTo($(this).parent());
fadeMyContent();
});
}, 3000)
}
fadeMyContentDummy()
})
});
DEMO

setInterval and clearInterval javascript not working as needed

I have the following code partially working. I am newbie in javascript so please don't blame me if my approach is not the best.
window.url_var = "status.htm";
window.elem = "#e1";
function menu_item(){
$(window.elem).click(function (event)
{
$("#divTestArea1").load(window.url_var);
});
}
$("#e1").click(function (event)
{
event.preventDefault();
window.url_var = "demo2.txt";
window.elem = "#e1";
$("#divTestArea1").load(window.url_var);
auto_refresh = setInterval(menu_item(), 5000);
});
$("#e2").click(function (event)
{
event.preventDefault();
window.url_var = "status.htm";
window.elem = "#e2";
$("#divTestArea1").load(window.url_var);
auto_refresh = setInterval(menu_item(), 5000);
});
$("#e3").click(function (event)
{
event.preventDefault();
window.url_var = "form.htm";
window.elem = "#e3";
clearInterval(auto_refresh);
$("#divTestArea1").load(window.url_var);
});
jQuery(document).ready(function() {
$("#divTestArea1").load(window.url_var);
auto_refresh = setInterval(menu_item(), 5000);
});
Whenever I click elements e1 and e2, the setInterval works as expected and as soon as I click element e3, the element cease to be reloaded.
That's the behavior I want so far. But I also wants to start the setinterval again if e1 or e2 get's again clicked.
the last is what it's not working on the above code.
I will appreciate if you could point me in the right direction.
I have come to this code after seeing some of the answers to my original question (thanks to everyone). To clarify my original idea, I need to update some items on my web page on a regular basics but the content can be change with some menu and also some of the contents like a form should not be updated.
window.url_var = "demo2.txt";
var auto_refresh = null;
function setRefresh() {
var self = this;
this.bar = function() {
if(window.url_var != ""){
$("#divTestArea1").load(window.url_var);
auto_refresh = setTimeout(function() { self.bar(); }, 5000);
}
}
this.bar();
}
$("#e1").click(function (event)
{
event.preventDefault();
window.url_var = "demo2.txt";
setRefresh();
});
$("#e2").click(function (event)
{
event.preventDefault();
window.url_var = "status.htm";
setRefresh();
});
$("#e3").click(function (event)
{
event.preventDefault();
window.url_var = "form.htm";
$("#divTestArea1").load(window.url_var);
window.url_var = "";
});
$(document).ready(function() {
setRefresh();
});
Try using 2 different variables and clearing all if needed. This is: auto_refresh1 and auto_refresh2. Each time you call setinterval, it creates a new timer with a new id. You are overwriting auto_refresh variable and the timer before that will still fire.
Or you can store the setinterval in a hash object and run through and clear them all.
I'm unclear as to what exactly it is that you're trying to do here. Nevertheless, I've rewritten your code a bit to make some improvements (and fix one glaring bug in your code involving the setInterval calls).
var url_var = "status.htm",
elem = "#e1",
$destination = $("#divTestArea1"),
auto_refresh;
function menu_item() {
$(elem).bind("click", function (e) {
$destination.load(url_var);
});
}
function load() {
$destination.load(url_var);
}
function set(url, id) {
url_var = url;
elem = id;
}
function setRefresh() {
return setInterval(menu_item, 5000);
}
function handleClick(e) {
e.preventDefault();
set(e.data.url, e.data.id);
load();
auto_refresh = setRefresh();
}
$("#e1").on("click", {
url: "demo2.txt",
id: "#e1"
}, handleClick);
$("#e2").on("click", {
url: "status.htm",
id: "#e2"
}, handleClick);
$("#e3").on("click", function (e) {
e.preventDefault();
set("form.htm", "#e3");
clearInterval(auto_refresh);
load();
});
$(document).ready(function () {
load();
auto_refresh = setRefresh();
});
I'm guessing that maybe those setInterval calls should actually be setTimeout calls? Why would you want to bind a "click" event handler over and over again?
EDIT #1: Switched to jQuery's currently preferred on method from the bind method, included use of event data parameter to further abstract event handling code.

Why doesn't the clearInterval() works?

I'm new to JavaScript and I'm having problems with this script.
it's part of a web game and the script is suppose to refresh the page until the player wins or loses.
for some reason it doesn't stop refreshing, I put an alert function to check if the functions works, and i get the alerts but it's still continue refreshing the page.
what am i doing wrong?
var t;
$(document).ready(function () {
intervals();
});
function intervals() {
t = self.setInterval('refreshData()', 10000);
}
function youWin() {
var f = $('#status:contains("YOU ARE THE WINNER!")');
if (f.length > 0) {
alert("YOU ARE THE WINNER!");
t = clearInterval(t);
}
}
function youlose() {
var f = $('#status:contains("You lost!")');
if (f.length > 0) {
alert("You lost!");
t = clearInterval(t);
}
}
function refreshData() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame');
youWin();
youlose();
}
You need to fix the reference to self and fix the .load() call.
.load() is asynchronous so it does not complete before you call youWin() and youLose() right after it. You need a completion function so you can check winning or losing after the .load() completes successfully.
refreshData() should be structured like this:
function refreshData() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame', function() {
youWin();
youlose();
});
}
You also should change this:
t= self.setInterval('refreshData()',10000);
to this:
t = window.setInterval(refreshData, 10000);
I don't see that self was even defined so that could have also been causing your problem and you should use the function reference directly rather than put in a string.
And, as a cleanup issue, you should change both occurences of this:
t = clearInterval(t);
to this:
clearInterval(t);
Here's a cleaned up version of the code that also eliminates global variables and unnecessary function definitions:
$(document).ready(function() {
var t = window.setInterval(function() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame', function() {
youWin();
youlose();
});
}, 10000);
function youWin() {
if ($('#status:contains("YOU ARE THE WINNER!")').length) {
alert("YOU ARE THE WINNER!");
clearInterval(t);
}
}
function youlose() {
if ($('#status:contains("You lost!")').length) {
alert("You lost!");
clearInterval(t);
}
}
});

Categories

Resources