I have a onload function in jquery like:
$(function () {
$('.over').hover(function () {
//FIRST PARAMETER RIGT, LEFT, TOP, BOTTOM
if ($(this).attr('data-direction') == 'right') {
$(this).addClass('flipping-right');
}
else if ($(this).attr('data-direction') == 'left') {
$(this).addClass('flipping-left');
}
else if ($(this).attr('data-direction') == 'top') {
$(this).addClass('flipping-top');
}
//ETC.
//SECOND gal1,gal2,gal3,gal4
if ($(this).attr('gal') == 'gal1'){
img = $(this).find('img');
setTimeout(function() {
img.attr('src', arrFirstYellowCard[i]);
i++;
if(i > arrFirstYellowCard.length-1)
i=0;
}, 100);
}
else if ($(this).attr('gal') == 'gal2'){
img = $(this).find('img');
setTimeout(function() {
img.attr('src', arrSecondPurpleCard[j]);
j++;
if(j > arrSecondPurpleCard.length-1)
j=0;
}, 100);
}
I want a function to execute that function every second but with parameters in array like
var array_param = ["right,gal1","top,gal3","bottom,gal4","left,gal2","right,gal5"];
which are allowed combinations
I want like a timer so each parameter is called every second
var timer = $.timer($('.over').hover(array_param( 0 ) ), 1000);
timer.play();
but I do not know how to implement this function, and how to add parameters to a function allocated in onload :
$(function () { $('.over').hover(function () {...
Please take a look at my jsfiddle
You can't trigger ready again. You can create a named function and call it a bunch.
$(function () {
index = 0;
window.setInterval(function () {
if (index > array_param.length) index = 0;
myFunction(array_param[index++]);
}, 1000); // call myFunction every second
});
myFunction = function (image) {
$('.over').hover(function () {
// rest of your code goes here
...
};
Related
I have a function that uses setInterval, and it keeps running and it doesn't want to stop. The code I wrote is
let findGrid = setInterval(function () {
if (grid == null) {
grid = $('#QuickEntryGrid').getKendoGrid();
}
else {
clearFindGrid;
console.log("Found Grid");
console.log(grid.dataSource.view());
}
}, 100);
let clearFindGrid = function () {
clearInterval(findGrid);
};
if (grid != null) {
grid.setOptions({
width: (newInnerVerticalWidth - 2) + "px"
});
$("#QuickEntryGrid").find("table").on("keydown", onGridKeydown);
}
It keeps hitting the console.log(grid.dataSource.view());
You must call the funcion with the brakets clearFindGrid()
I have some code I am using to countdown from 15 after 15 secs passes it echoes "times over". The problem is if someone clicks twice there will be two counters in the same Div. I need the counter to reset if someone clicks on the button again.
function startCountDown(i, p, f) {
// store parameters
var pause = p;
var fn = f;
// make reference to div
var countDownObj = document.getElementById("countDown");
if (countDownObj == null) {
// error
alert("div not found, check your id");
// bail
return;
}
countDownObj.count = function (i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
// stop
return;
}
setTimeout(function () {
// repeat
countDownObj.count(i - 1);
},
pause);
}
// set it going
countDownObj.count(i);
}
function myFunction() {
alert("Time Over");
}
HTML:
<div id="TimerTitle">Timer</div>
<span id="countDown"></span>
<button onclick="startCountDown(15, 1000, myFunction);">
Start Time
</button>
Set the timeout as a global variable like so:
timer = setTimeout(function(){countDownObj.count(i - 1);},pause);
At the beginning of the function clear the timeout
clearTimeout(timer)
Code:
var timer;
function startCountDown(i, p, f) {
// store parameters
if(timer){clearTimeout(timer)}
var pause = p;
var fn = f;
// make reference to div
var countDownObj = document.getElementById("countDown");
if (countDownObj == null) {
// error
alert("div not found, check your id");
// bail
return;
}
countDownObj.count = function (i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
// stop
return;
}
timer = setTimeout(function(){countDownObj.count(i - 1);},pause);
}
// set it going
countDownObj.count(i);
}
function myFunction() {
alert("Time Over");
}
setTimeout returns an id to the timer that can be used with window.clearTimeout. The simplest solution would be to create a global timerId
var timerId;
...
function startCountDown(i, p, f) {
...
if (timerId) { window.clearTimeout(timerId); }
timerId = window.setTimeout(...);
https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout
I've used this
http://jsfiddle.net/3KydB/
and tried to modify it for 3 divs:
window.switchIn = function () {
$('.chart_1').fadeToggle(function() {
$('.chart_2').fadeToggle(function() {
$('.chart_3').fadeToggle(function() {
setTimeout(function() {window.switchOut();}, 6000);
});
});
});
}
window.switchOut = function () {
$('.chart_3').fadeToggle(function() {
$('.chart_2').fadeToggle(function() {
$('.chart_1').fadeToggle(function() {
setTimeout(function() {window.switchIn();}, 6000);
});
});
});
}
setTimeout(function() {window.switchIn();}, 6000)
The first one fades in and out fine, then the second one fades in with the third one below it, then back to the first one etc.
I think you would want something like the following: http://jsfiddle.net/mEeAt/
window.switch1 = function () {
$('.chart_3').fadeToggle(function() {
$('.chart_1').fadeToggle(function() {
setTimeout(window.switch2, 6000);
});
});
}
window.switch2 = function () {
$('.chart_1').fadeToggle(function() {
$('.chart_2').fadeToggle(function() {
setTimeout(window.switch3, 6000);
});
});
}
window.switch3 = function () {
$('.chart_2').fadeToggle(function() {
$('.chart_3').fadeToggle(function() {
setTimeout(window.switch1, 6000);
});
});
}
setTimeout(window.switch2, 6000)
So each function is responsible for fading out the active element, fading in the next element, and setting a timeout for the next function in the cycle.
Of course there is a lot of repeated code here, so you would probably be better off creating a function to make this more generic: http://jsfiddle.net/mEeAt/1/
function cycle(delay) {
var elements = Array.prototype.slice.call(arguments, 1);
var functions = [];
for (var i = 0; i < elements.length; i++) {
functions.push(function (i) {
var prev = i === 0 ? elements.length - 1 : i - 1;
var next = (i + 1) % elements.length;
return function() {
elements[prev].fadeToggle(function() {
elements[i].fadeToggle(function() {
setTimeout(functions[next], delay);
});
});
};
}(i));
}
functions[1](); // start cycle by fading in the second element
}
cycle(6000, $('.chart_1'), $('.chart_2'), $('.chart_3'));
The glowing CSS effect is:
//Public Variables.
var clear_interval;
var stop_set_time_out;
function record_css_effect() {
clear_interval = setInterval(
function() {
rec_block.css('background-color', "red");
stop_set_time_out = setTimeout(function() {
rec_block.css('background-color', "green");
}, 500)
}, 1000);
};
And in another function, I call:
function stop_record() {
alert("Stop record.");
clearTimeout(stop_set_time_out);
clearInterval(clear_interval);
}
The glowing only stops first time.
The second time, I didn't call record_css_effect() function yet the glowing effect happened automatically...
which would mean that the clearTimeout and clearInterval don't work...
Why is that, and How can I achieve it?
UPDATE:
Actually, I use clearInterval( clear_interval ); in many places.
As the user want to take record,they press on a button, and pop_record_window() is then called.
function pop_record_window()
{
$('#start_and_stop_rec').click
(
function(){ record_voice(); }
)
}
function record_voice()
{
record_css_effect();
REC= $("#start_and_stop_rec");
if(REC.prop("value")=="record")
{
alert("Start to record");
alert( dir_path + User_Editime + "/rec"+"/" + "P" + current_page + "_" + records_pages_arr[current_page].get_obj_num() +".mp3");
current_rec_path= dir_path + User_Editime + "/rec"+"/" + "P" + current_page + "_" + records_pages_arr[current_page].get_obj_num() +".mp3";
cur_record_file= new Media(current_rec_path,onSuccess, onError);
cur_record_file.startRecord();
$('#stop_rec').bind("click", function(){
clearTimeout( stop_set_time_out );
clearInterval( clear_interval );
});
REC.prop("value","stop");
}
else if(REC.prop("value") == "stop")
{
stop_record();
cur_record_file.stopRecord();
clearInterval( clear_interval );
//make visibility hidden!
REC.prop("value","record");
}
};
But since the second time, the user didn't press on the button: start_and_stop_rec, the glowing effect fires. However, the code within
if(REC.prop("value")=="record") condition doesn't execute.
If you call record_css_effect() multiple times multiple intervals might start but only the last interval-id will be stored in clear_interval. By ensuring only 1 interval is running at a time you can prevent this from happening.
//Public Variables.
var clear_interval;
var stop_set_time_out;
function record_css_effect() {
if (clear_interval !== null) // if a timer is already returning don't start another
return;
clear_interval = setInterval(function () {
rec_block.css('background-color', 'red');
stop_set_time_out = setTimeout(function () {
rec_block.css('background-color', 'green');
}, 500)
}, 1000);
};
function stop_record() {
alert("Stop record.");
clearTimeout(stop_set_time_out);
clearInterval(clear_interval);
stop_set_time_out = clear_interval = null;
}
You can also make your code a bit simpler (by removing the setTimeout) to make it easier to debug, like so:
//Public Variables.
var clear_interval, isRed = false;
function record_css_effect() {
if (clear_interval !== null) // if a timer is already returning don't start another
return;
clear_interval = setInterval(function () {
if (isRed) {
rec_block.css('background-color', 'red');
isRed = false;
} else {
rec_block.css('background-color', 'green');
isRed = true;
}
}, 500);
};
function stop_record() {
alert("Stop record.");
clearInterval(clear_interval);
clear_interval = null;
}?
(function() {
var count = {
digit: 0,
increment: function() {
var interval = setInterval(function() {
if (++count.digit == 10) {
clearInterval(interval);
count.decrement();
}
var update = document.getElementById("liveUpdate");
update.innerHTML = count.digit;
}, 500);
},
decrement: function() {
var interval = setInterval(function() {
if (--count.digit == -1) {
clearInterval(interval);
}
}, 500);
}
};
count.increment();
})();
It stops but it doesn't go down? What could be the problem?
Your decrement function never updates the output anywhere. The variable is going down but you don't show that on screen.
Try (or check the corresponding JSFiddle):
(function() {
var update = document.getElementById("liveUpdate");
var count = {
digit: 0,
increment: function() {
var interval = setInterval(function() {
if (++count.digit == 10) {
clearInterval(interval);
count.decrement();
}
update.innerHTML = count.digit;
}, 500);
},
decrement: function() {
var interval = setInterval(function() {
if (--count.digit == -1) {
clearInterval(interval);
}
update.innerHTML = count.digit;
}, 500);
}
};
count.increment();
})();
setInterval will call the function every 500 seconds. It will not stop until you stop it. You can read more about stopping it at Stop setInterval call in JavaScript
It't not a bug, it's a feature ;-). setInterval() runs the given function in a loop with a given interval (500 ms). See this article for details.