call a function with different parameters in setInterval - php

I am using setInterval function to call a function after a particular time intervals.
Code is given below:
var refreshIdd = setInterval(function() {
loadData(page);
}, <?= $h; ?>);
For example: If the time interval ie $h is 1000(1 sec) I have to call the function loadData with parameter 1. In the second second i have to call loadData 2.In Each time interval I have to pass 1,2,3 etc.If the $h is 2000 ie 2sec,I have to call loadData after 2nd second with parameter 1 and with parameter 2 in 4th second and so on
How can I do this?

This is independent of $h.
Set page = 1 and do a simple increment with page++. This would increase the value of page by 1 every time it is called.
var page = 1;
var refreshIdd = setInterval(function() {
loadData(page++);
}, <?=$h?>);
See simple demo.

You can create a separate function to get diff params.
var paramValue = 0;
var refreshIdd = setInterval(function() {
param = getParam();
loadData(param);
}, <?= $h; ?>);
function getParam() {
return ++paramValue;
}
(OR)
Simple as,
var paramValue = 0;
var refreshIdd = setInterval(function() {
loadData(++paramValue);
}, <?= $h; ?>);

Related

How can I display string elements received by json based on the date and time they should be displayed?

I have a database and I store there a text, its duration and time when it should appear on the webpage.
The result of the php is as follows:
{"text_content":"dgsgdsgds","text_duration":"15","start_time":"2015-09-28 23:11:15"},{"text_content":"dgsgdsgds","text_duration":"15","start_time":"2015-09-28 23:11:30"},{"text_content":"gdsgdsgds","text_duration":"15","start_time":"2015-10-01 14:00:00"}
I have a jquery script that fetches the data from the database and prints it on the screen:
var results =[];
var cursor = 0;
function myFunction () {
$.getJSON('list2.php', function(json) {
results = json;
cursor = 0;
// Now start printing
printNext();
});
}
function printNext(){
if(cursor == results.length){
// Reset the cursor back to the beginning.
cursor = 0;
}
// Print the key1 in the div.
//$('#mydiv').html(results[cursor].key1);
$('#mydiv').hide('fast', function(){ $('#mydiv').html(results[cursor].text_content); $('#mydiv').show('fast'); });
// Set a delay for the current item to stay
// Delay is key2 * 1000 seconds
setTimeout(function(){
printNext();
}, results[cursor].text_duration * 1000);
// Advance the cursor.
cursor++;
}
and now I wanted to add a feature that text displays on the screen only on a date that is fetched from database, as start_time, but I'm not sure if it's possible to do on jquery only, without any further access to the server code..
I tried adding some if statement like:
if(results[cursor].start_time == new Date()){
just before printing it on the screen but it didn't do the trick. Could you help me with that?
Thanks!
Parse your json string with JSON.parse:
var myObj = JSON.parse(results[0]);
and compare your start_time:
if (new Date(myObj.start_time) == new Date())
if you want run your function on specific time use setTimeout:
var diff = new Date(myObj.start_time).getTime() - new Date().getTime();
setTimeout(function() {
$('#mydiv').hide('fast', function() {
$('#mydiv').html(results[cursor].text_content);
$('#mydiv').show('fast');
});
}, diff)
or you can execute your function every 1000ms by using setInterval and stop it with clearInterval:
function check() {
if (new Date(myObj.start_time) == new Date()) {
$('#mydiv').hide('fast', function() {
$('#mydiv').html(results[cursor].text_content);
$('#mydiv').show('fast');
});
clearInterval(myInterval);
}
}
var myInterval = setInterval(check, 1000)

Give parameters to a function called by setInterval

I have the following function:
<script>
var count=900;
var countM;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
function timer()
{
count=count-1;
countM=Math.floor(count/60);
if (count <= 0)
{
clearInterval(counter);
return;
}
for(var i=0; i<10; i++)
{
document.getElementById("timer"+i).innerHTML=countM+"mins. "+(count%60)+ " secs"; // watch for spelling
}
}
</script>
And I am displaying it like this:
<span id="<?php echo "timer".$theCounter; ?>"></span>
$theCounter++;
The problem its that I want to call it giving it a parameter, which will be count and I have no idea how to do it.
'I want to call it giving it a parameter, which will be "count"'
Something like the following:
function createTimer(count) {
var countM,
counter=setInterval(timer, 1000);
function timer()
{
count -= 1;
countM = Math.floor(count/60);
if (count <= 0) {
clearInterval(counter);
return;
}
for(var i=0; i<10; i++) {
document.getElementById("timer"+i).innerHTML=countM+"mins. "+(count%60)+ " secs";
}
}
}
...will give you a function, createTimer(), that you can call with a parameter for the count:
createTimer(900);
If you're saying you want different spans to have different counters then you can do this:
function createTimer(count, elementID) {
// code exactly the same as above function except
// remove the `for` loop and just reference the elementID
// passed into the function:
document.getElementById(elementID).innerHTML=countM+"mins. "+(count%60)+ " secs";
}
createTimer(900, 'timer1');
createTimer(200, 'timer2');
// etc.
Demo: http://jsfiddle.net/dUTk3/1/
Like this?
var counter = window.setInterval(function() {
timer('parameter');
}, 1000);
I do not see what is the relationship between the javascript and PHP parts.
Use the bind function prototype to create a function with default parameters.
timer.bind(null,count-1);
The first argument is function context (null means global), optional following parameters is set tho function arguments from left. The result is new function. So in your code:
function timer(count) {
console.log(count); // do some stuff
if(count>0) setTimeout(timer.bind(null,count-1),1000);
}
timer(10); // counts from 10 to 0 in 1s interval
See the fiddle

JavaScript Countdown (counting up) milliseconds too quick, wont load next page?

javascript too fast when i set setInterval(function() down (or up i guess, speed wise) to 100 or 500 and wont load mypage.php as it doesn't have time i think? don't want to slow counter down either. so is there a php equivalent that can? (with the little number display like this, see jsfiddle) or is there a better javascript counter ? would prefer php, any ideas?
Thanks heaps, any help would be great.
Changed the page link to # as it will freeze things otherwise
http://jsfiddle.net/aEXgB/2/ Also added exit;but didn't help.
<html>
<head>
<script type="text/javascript">
function countdown() {
var i = document.getElementById('counter');
if (parseInt(i.innerHTML)>=3000) {
location.href = 'mypage.php';
exit;
}
i.innerHTML = parseInt(i.innerHTML)+1;
}
setInterval(function(){ countdown(); },.75);
</script>
</head>
<body>
<div style="margin-left:20px; float:left;"><p>Countdown:<font color="#33CC00"> <span id="counter">10 </span></font></p></div>
</body>
</html>
replace
setInterval(function(){ countdown(); },.75);
with
var t = setInterval(function(){ countdown(); },.75);
then just before the exit in the function, add;
clearInterval(t);
First, I don't understand why it's called a countdown when you count UP.
Second, I think it's better to update the counter and THEN check the value. That way you don't have an extra call to the coundown function.
Third, clear the interval before changing location because the interval is probably getting fired again too quickly.
Fourth, this won't actually work in jsfiddle because of how jsfiddle uses iframes :)
var interval = setInterval(function(){ countdown(); },.75);
function countdown() {
var i = document.getElementById('counter');
i.innerHTML = parseInt(i.innerHTML)+1;
if (parseInt(i.innerHTML)>=3000) {
clearInterval(interval);
window.location.href = "mypage.php";
}
}
JS:
var sec = 0;
var interval = 750; // milliseconds
var stop = 5; // seconds
function pad ( val ) { return val > 9 ? val : "0" + val; }
setInterval( function(){
if(document.getElementById("seconds").innerHTML < stop) {
document.getElementById("seconds").innerHTML=pad(++sec%60);
} else {
location.href = 'http://google.nl'
}
}, interval);
Html:
<div id="seconds></div>
Fiddle:
http://jsfiddle.net/5tM3A/5/

Call a function outside of a dynamic jquery slider

I am dynamically creating my sliders and in the "Slide" event and "Stop" event I would like to call a function that is defined in the non dynamic content. I can get the functions to work if I create them each time with the slider, but that seems like a lot of redundant code?
Non Dynamic function
$(document).ready(function() {
var converSecondsToMinutes;
convertSecondsToMinutes = function(secondsEntered){
var secondsEntered = secondsEntered;
var time = parseInt(secondsEntered,10);
time = time < 0 ? 0 : time;
var minutes = Math.floor(time / 60);
var seconds = time % 60;
minutes = minutes < 9 ? "0"+minutes : minutes;
seconds = seconds < 9 ? "0"+seconds : seconds;
var newTime = minutes+":"+seconds
console.log(newTime);
return newTime
}
});
Dynamic jQuery slider
<?php
query...
result...
for(...){
?>
<Script>
$( "#slider"+<?php echo $id; ?> ).slider({
animate: true ,
value: 0,
min: 0,
//dynamic grab this
max: <?php echo $playtime_seconds; ?>,
step: 0.01,
start: function( event, ui ) {
....
},
slide: function( event, ui ) {
audio = ....
audio.currentTime = ui.value;
progress_seconds = parseFloat(audio.currentTime.toFixed(2));
progress_seconds = $(function(){convertSecondsToMinutes(progress_seconds);});
$('#progress_seconds'+<?php echo $id; ?>).html(progress_seconds);
},
stop: function( event, ui ) {
....
}
}
});
});
}
I cut and paste the parts of the code that were important to the question.
This is the line that is not working: $('#progress_seconds'+).html(progress_seconds);
You edited just after I commented, so my comment no longer made sense, the $(function(){ part of your code is not necessary, try just using:
progress_seconds = converSecondsToMinutes(progress_seconds);
And spelling errors in code are a real issue with me, conver has a t at the end.
There is also no need to wrap your function in $(document).ready(), declare it like this:
function convertSecondsToMinutes(secondsEntered)
{
var time = ...
...
}

How to load more on PHP array?

I use jQuery (I found this code in an answer, tested and working) to show people.php and reload it every 100 seconds. People.php has an array peoples where there are saved name, job, birthday.
As you can see, the output stops at 30 names. How can I have a twitter like button "load more" and show 10 more at a time? Additionally, when there are e.g. 50 more people's name (assuming that the user clicked "load more" twice, will the jQuery timeout reload, returned them at 30 as the beginning ?
<script>
var timerID;
$(function () {
function loadfeed() {
$('#feed')
.addClass('loading')
.load('people.php', function () {
$(this).removeClass('loading');
timerID = setTimeout(loadfeed, 100000);
});
}
loadfeed();
});
</script>
How about passing a parameter to the URL in your load(..) call?
$(function () {
var startAt = 0;
function loadfeed() {
$('#feed')
.addClass('loading')
.load('people.php?start_at=' + startAt, function () {
$(this).removeClass('loading');
timerID = setTimeout(loadfeed, 100000);
startAt += 30;
});
}
});
Then in people.php you could get the passed parameter using $_GET:
$start_at = 0;
if (isset($_GET['start_at']) && is_numeric($_GET['start_at'])) {
$start_at = (int) $_GET['start_at'];
}
for ($i = $start_at; $i < min($start_at + 30, sizeof($peoples)); $i++) {
echo $peoples[$i]->name;
}
Well what you could do is save a variable that contains the number of people, this example should give you a good view of what i mean.
<script>
var timerID;
var cap;
$(function () {
function loadfeed() {
$('#feed')
.addClass('loading')
.load('people.php?cap='+cap, function () {
$(this).removeClass('loading');
timerID = setTimeout(loadfeed, 100000);
});
}
loadfeed();
});
</script>
<?php
foreach ($peoples as $people) {
if(++$i > $_GET['cap']) break;
echo $people->name;
}
?>
So all you have to do, is change the cap variable, you could do this easily making a javascript function and call this via a onClick event.

Categories