high CPU usage after JavaScript setInterval - javascript

I am having a PHP code which pulls out text from the database, and shows it in a div as links. I am refreshing that DIV every 3000 milliseconds, and the CPU usage is only a few percent higher upon the refresh itself. After 20-25 minutes of constant refreshes, when I click on one of the links, it takes about 20 seconds to open that page, and meanwhile the browser tab freezes up. More refreshes occur - more time it takes to open a link, as well as when more links are opened (if 10-15 links are opened, it gets as slow as 10-12 seconds to open next page). When browser is trying to open the link, 1 processor thread is fully loaded. Here is the code (simplified):
<div id="map1"></div>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<div id="map1">
<?PHP
if (isset($_GET['m'])) {
$selectback = "SELECT parentid FROM MAP_LINK WHERE sysid = " . $_GET['m'];
................
$rowb = ibase_fetch_row($query);
echo "<h6>BACK</h6><h4>
<script>
$('a#back" . $rowb[0] . "').click(function() {
clearInterval(auto_refresh);
$(\"#map1\").load(\"test2.php?m=" . $rowb[0] . "\");
auto_refresh = setInterval(function (){
$(\"#map1\").load(\"test2.php?m=" . $rowb[0] . "\");}, 3000);
});
</script>";
$select = "SELECT sysid FROM MAP_LINK WHERE parentid = " . $_GET['m'];
.........................................
$x = 0;
while ($x < $total_rows) {
$x++;
$row = ibase_fetch_row($query);
echo "<br>Link # " . $row[0] . "
<script>
$('a#" . $row[0] . "').click(function() {
clearInterval(auto_refresh);
$(\"#map1\").load(\"test2.php?m=" . $row[0] . "\");
auto_refresh = setInterval(function (){
$(\"#map1\").load(\"test2.php?m=" . $row[0] . "\");}, 3000);
});
</script>";
}
} else {
echo "<script>
$(document).ready(function(){
$(\"#map1\").load('test2.php?m=56');
auto_refresh = setInterval(function (){
$(\"#map1\").load(\"test2.php?m=56\");}, 3000);
});</script>";
}
?>
This is about the same code I have. The database consists of 4 tables where data is pulled from. The first 6-7 clicks open next page momentarily with no delay, delays start after the 10th click and get bigger with each additional click or refresh.
My question is: How can I make it open immediately or at least faster? There is an error in code. It works, but it's using the CPU a lot and is getting slow enough to not being to navigate on page.
Thank you!

Late for help but you could try chaining setTimeouts together, like this:
function refreshments() {
setTimeout(function(){
//Do stuff
refreshments();
}, 1000);
}
refreshments();

Related

how to use "setInterval" with "while loop".?

I check all documants about setinterval from forum but.. I couldnt find what I want... Here is my question.:
my code is below:
<?php
include('database_connection.php');
$sorgu = $baglanti->query("select * from makale");
while ($sonuc = $sorgu->fetch_assoc()) {
?>
MY TABLE CODE HERE.. ( codes like : <?php echo $sonuc['proje_ismi'] ?> )
<?php } ?>
I call datas to my table from mysql.. But I change database from admin panel..
And What I want is when I change some data from adminpanel... My users will see it immediatly in few sec with setInterval code without refreshing page...
How can I do that in my documants?
The simplest thing you can do is to refresh the page automatically after few seconds:
<script>
// Auto-refresh the page after 5 seconds:
setTimeout(function() {
document.location.reload(true);
}, 5000);
</script>

refresh modal window without closing it

I have image thumbnails in 100s of directories. I am using PHP to retrieve the images. A bootstrap modal with id #imagePalette window pops up on clicking a button and displays all the images in the directory.
In javascript
$.post('getCroppedImages.php',{'location': location, 'brand':brand},function(data) {
var imagemodal = $('#imagePalette');
imagemodal.find('.modal-title').html('Brand: ' + brand + ' in ' + location);
imagemodal.find('.modal-body').html(data).show();
});
PHP code that retrieves the images:
$path = "projects/" . $database . '/' . $match . '/' . $location . '/' . $brandname . '/*.jpg';
$files = glob($path);
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
$filname = basename($num, ".jpg");
$imgname = basename($num);
$img = $path . $imgname;
$filnam = substr($filname, -9,9);
$filnam = rtrim($filnam);
echo '<ul class="croppeditem" id="croppeditem">';
echo '<li style="list-style:none;cursor:pointer" ><img onclick="clickCroppedImage(this.id); return false"; src="'.$num.'" id="'.$filnam.'"/>';
echo '<figcaption class="caption" name="caption">' . $filnam . '</figcaption>';
echo '</li></ul>';
}
The above code works perfectly. It displays the images. I have a function clickCroppedImage attached to each image. When the user clicks on a image in the modal window, this function triggers another php that deletes the image from the folder.
This deletion also works without any trouble. I am trying to refresh the modal modal without closing it so that the current set of images in the folder gets displayed. I have written similar php and javascript code and used unlink to delete the image from the folder.
In Javascript
$.post('deleteAnnCroppedImage.php', {'folder':wd, 'matchLst':matchLst, "imgPath" : clickedImg, 'currentAnnotCheckLocation': currentAnnotCheckLocation, 'currentAnnotCheckBrand': currentAnnotCheckBrand}, function(data){
//imagemodal.find('.modal-body').html().show();
var imagemodal = $('#imagePalette');
imagemodal.find('.modal-body').html("");
imagemodal.find('.modal-body').html(data).show();
});
PHP Code
$currentAnnotPath = "projects/" . $database . '/' . $match . '/' . $location . '/' . $brandname . '/*.jpg';
$files = glob($currentAnnotPath);
$imgPath = $_POST['imgPath'];
unlink($imgPath);
//echo "Deleted Image";
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
$filname = basename($num, ".jpg");
$imgname = basename($num);
$img = $currentAnnotPath . $imgname;
$filnam = substr($filname, -9,9);
$filnam = rtrim($filnam);
echo '<ul class="croppeditem" id="croppeditem">';
echo '<li style="list-style:none;cursor:pointer" ><img onclick="clickCroppedImage(this.id); return false"; src="'.$num.'" id="'.$filnam.'"/>';
echo '<figcaption class="caption" name="caption">' . $filnam . '</figcaption>';
echo '</li></ul>';
}
The php scripts returns the ul li data correctly which I can print to console. However, I am not able to refresh the modal body and display the returned images. I tried different combinations, but the modal window does not show any reaction.
How do I clear the modal body and reload the images without closing the modal window?
You will have to use AJAX if I understood your problem correctly.
After a user deleted an image you have to trigger a AJAX request and change the content of the modal.
A good introduction to AJAX can be found via google.
Best regards
You should be able to reach the modal-body element.
First of all make sure you can see it from the current function scope.
Sample codes that are working with the basic bootstrap modal:
Pure JS:
document.getElementsByClassName('modal-body')[0].innerHTML = '<p>some html</p>';
jQuery:
$('#imagePalette .modal-body:first').html('<p>some html</p>');
If there is an iFrame and the modal is inside than you should get into the iFrame document first from JavaScript.
Other:
In these cases you can use jQuery wrapper instead of introducing a new variable. You won't loose performance but it will make this code more readable.

Scroll to bottom of item on Ajax load

I am creating a kind of messaging system with php and jQUERY, when you click on users profile and hit the messaging button it take us to the message page, it takes about 2sec to load previous message, so I added a code to scroll to bottom of the div class containing all message item once the ajax is loaded, to show latest messages , but the problem I am having is when I try to scroll up back I am having issues , the moment i try to scroll up due to the code i added it goes down on its own, any solution would be well appreciated.
Here is my JQ code - if there is anything else I can provide to help me solve this issue, I would do so quickly.
$(document).ready(function(){
/*post message via ajax*/
//get message
var c_id = $("#conversation_id").val();
//get new message every 2 second
setInterval(function(){
$(".display-message").load("get-message-ajax.php?c_id="+c_id , stateChange);
}, 2000);
});
function stateChange() {
var newstate = true;
if(newstate = true){
$(".conversation_history.clearfix").animate({
scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight
}, 1000)} else {
$(".conversation_history.clearfix").end();
var newstate = false;
}
}
Code from get_message-ajax.php
<?php
include 'db.php';
include 'function.php';
/*Get Message*/
if(isset($_GET['c_id'])){
$conversation_id = base64_decode($_GET['c_id']);
$querynew = "SELECT * FROM `messages` WHERE conversation_id='$conversation_id'";
$mysqli_q_new = mysqli_query($connection, $querynew);
confirmQuery($mysqli_q_new);
if (mysqli_num_rows($mysqli_q_new) > 0 ){
while($user_real_info = mysqli_fetch_assoc($mysqli_q_new)){
$trap_user_from = $user_real_info['user_from'];
$trap_user_to = $user_real_info['user_to'];
$trap_user_message = $user_real_info['message'];
$querynew2 = "SELECT profile_image,firstname FROM `users` WHERE id='$trap_user_from'";
$mysqli_q_new2 = mysqli_query($connection, $querynew2);
confirmQuery($mysqli_q_new2);
$user_fetch = mysqli_fetch_assoc($mysqli_q_new2);
$user_form_username = $user_fetch['firstname'];
$user_form_img = $user_fetch['profile_image'];
?>
<div class='conversation_history_inner clearfix'>
<span><?php echo $user_form_username; ?> </span>
<div class='converstion_history_image img-is-responsive pull-left'>
<?php echo getUserImage($user_form_img) ?>
</div>
<div class='converstion_history_chat'>
<p><?php echo $trap_user_message; ?></p>
</div>
</div>
<?php
}
}
} else {
echo 'nth found';
}
?>
I'm assuming you only want to scroll down when it gets the first message. If so, I would suggest changing the stateChange function into this:
var scrolled = false;
function stateChange() {
if(!scrolled){
$(".conversation_history.clearfix").animate({scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight}, 1000);
scrolled = true;
}
}
This will make it only scroll down the first time it gets a new message instead of every time like it currently does.
The content is scrolling to bottom automatically because you have used setInterval function which will trigger at a constant interval of time. Use setTimeOut instead it will call only once after the specified time. Look here for more details

ajax request makes page lag

I have this ajax request code
function hehe2(){
var a = $(".film2numb").val();
return $.ajax({
type : "GET",
url : "php/controller1.php?page=semuafilm",
data : "data="+a,
cache: false,
success: function(data){
$('.semuafilm').load('php/film.php');
},
});
}
and it requests this php code, basically it prints out HTML data from SQL
<?php
$indicator = $_SESSION['p'];
if ($indicator == 'filmbaru') {
# code...
$batas = $_SESSION['a'];
if (!$batas) {
$batas = 1;
}
if ($batas>1) {
$batas = $batas * 8;
}
include('connect.php');
$queryfilm = "select * from tb_film order by film_year desc, film_id desc limit $batas ,8";
$exec = $conn->query($queryfilm);
while ( $f = $exec->fetch_assoc()) {
$tn = str_replace(" ","-",$f['film_name']) ;
?>
<div class='col l3 m3 s6 itemovie'><div><img src="images/dum.jpg" class="lazy" data-original='http://www.bolehnonton.com/images/logo/<?php echo $f["film_logo"]; ?>' width="214" height="317"><div><div><div><p><b><?php echo $f['film_name']; ?></b></p><p>IMDB Rating</p><p><?php echo $f['film_genre']; ?></p><p class='center-align linkmov'><a class='dpinblock browntex' href='?page=movie&filmname=<?php echo $tn; ?>'>PLAY MOVIE</a></p><p class='center-align linkmov'><a class='dpinblock' href=''>SEE TRAILER</a></p></div></div></div></div></div>
<?php
}
?>
and here is the controller
<?php
session_start();
$a = $_GET['data'];
$p = $_GET['page'];
$g = $_GET['genre'];
$_SESSION['a'] = $a;
$_SESSION['p'] = $p;
$_SESSION['g'] = $g;
?>
My question is why every time I click button that binded to the hehe2() function (4-5 times, which requested a lot of images) the page get heavier as I click incrementally(laggy, slow to scroll), is there a way to make it lighter, or is there a way to not store image cache on page or clear every time I click the button that binded to hehe2() function?
I am not sure that my advice will be helpful, I will just share my experience.
First of all you should check your binding. Do you bind click trigger only once?
Sometimes function binds multiple times and it can slow down the page.
You can put code below inside function and check the console
console.log("Function called");
If everything is fine from that point and function fires only once - I would recommend you to change flow a little bit. Is it possible to avoid many clicks in a row? If it is not big deal - you can disable button on click, show loader and enable button when AJAX request is completed. This approach will prevent from making multiple requests at once at page will be faster.

CountDown Timer Before Redirect In Pure PHP

I am using a pure JavaScript count down timer that I shared below to redirect to a URL after some time and show the left time to visitor also.
DEMO: JSFiddle
<form name="redirect" id="redirect">
You Will Be Redirected To Next Page After <input size="1" name="redirect2" id="counter"></input>Seconds.
</form>
<script type="text/javascript">
var countdownfrom=5
var currentsecond=document.redirect.redirect2.value=countdownfrom+1
function countredirect(){
if (currentsecond!=0){
currentsecond-=1
document.redirect.redirect2.value=currentsecond
}
else{
showIt()
return
}
setTimeout("countredirect()",1000)
}
countredirect()
function showIt() {
window.location.href = "http://jsfiddle.net/";
}
</script>
Now I want the same function and features and work in pure PHP as you know that many old mobile browsers still does't not support JavaScript and many are using JavaScript blocker. So Is this possible to do the same in Pure PHP, no <script> tags.
UPDATE:
I know the below codes but I want a count down timer too to show to the visitor.
<?php header('Refresh: 5; URL=http://jsfiddle.net/'); ?>
<meta http-equiv="refresh" content="5;url=http://jsfiddle.net/">
Answer:
This can't be done only with php you will need to use jquery or javascript with it. PHP is a server side scripting language you have to use client side language for this task.
Tip:
For redirecting purpose Just use header() function in php to redirect the php file in some time.Your code should look like this
<?php
header( "refresh:5;url=http://jsfiddle.net" );
?>
Hope this helps you...
Well if you want some output, you can't use header(). Alternatively, you could do something like this:
echo "<pre>";
echo "Loading ...";
ob_flush();
flush();
$x = 0;
while($x <= 4) {
$x++;
echo '<br/>'. $x;
ob_flush();
flush();
sleep(1);
}
echo '<meta http-equiv="refresh" content="0;url=http://jsfiddle.net/">';
PHP is a server-side language. You cannot control how the browser behaves from PHP without some quite complex setup. And even that, you cannot guarantee the behaviour of showing a countdown without JavaScript. For browsers who restrict JavaScript execution, the Refresh header will work just fine. However, for those having JavaScript enabled (which is the majority of browsers nowadays, desktop and mobile alike), a simple header will not give any UI feedback and is frustrating for users who expect responsive applications and web pages.
For this reason, JavaScript can be added, if available, to enhance the automatic, delayed, redirection and give the user some feedback of what's going on. Those with JavaScript disabled will just see a static page, telling them that the page will be redirected, and how long they have to wait for it.
PHP
<?php
$redirectTimeout = 5; // seconds
header('Refresh:' . $redirectTimeout . ';url=http://jsfiddle.net');
// ...
// inside your <head>, add this
echo '<meta http-equiv="refresh" ' .
'content="' . $redirectTimeout . ';url=http://jsfiddle.net">';
// ...
// inside your <body>, add this (or something similar)
echo '<div>' .
'You will be redirected to next page after ' .
'<span id="redirectCountdownLabel">' .
$redirectTimeout .
'</span> seconds' .
'</div>';
// ...
// add JS below
JavaScript
For this part, I recommend you use jQuery. It will not only write safer and cross-browser JS, it will also make your code smaller and prettier. This part can be put anywhere in your HTML, or inside a .js file that you add with a <script> tag. For convenience, you can even add jQuery using a CDN.
!function() {
$(function () {
var meta = $('head meta[http-equiv="refresh"]');
var label = $('#redirectCountdownLabel');
var loadTime;
var refreshTimeout;
if (meta.length && label.length) {
loadTime = window.performance.timing.domComplete;
refreshTimeout = parseInt(meta.attr('content'), 10); // seconds
new Timer(refreshTimeout * 1000, loadTime).start(200, function (elapsed) {
// "elapsed" ms / 1000 = sec
label.text(refreshTimeout - parseInt(elapsed / 1000));
});
}
});
function Timer(maxTime, startTime) {
var timeout;
var callback;
startTime = startTime || Date.now();
function nextTimer(delay) {
timeout = setTimeout(function () {
var curTime = Date.now();
var elapsedTime = curTime - startTime;
callback(elapsedTime);
if (elapsedTime < maxTime) {
nextTimer(delay);
}
}, delay);
}
this.start = function start(ms, cb) {
stop();
callback = cb;
nextTimer(ms);
};
this.stop = function stop() {
if (timeout) {
clearTimeout(timeout);
}
};
};
}();
(Note: here's a jsfiddle of the Timer class.)
scusate per prima, ho postato male, sono ali inizi, sorry
<?php
echo "<pre>";
echo "Loading ...";
ob_flush();
flush();
$x = 21;
while($x >= 1) {
$x--;
echo '<br/>'. $x;
ob_flush();
flush();
sleep(1);
}
echo '<meta http-equiv="refresh" content="0;url=http://jsfiddle.net/">';
To do the countdown, so it seems to work or am I wrong?
<?php
echo "Loading ...";
ob_flush();
flush();
$x = 21;
while($x >= 1) {
$x--;
echo '<br/>'. $x;
ob_flush();
flush();
sleep(1);
}
echo '<meta http-equiv="refresh"content="0;url=http://jsfiddle.net/">';
?>`

Categories

Resources