/    Sign up×
Community /Pin to ProfileBookmark

pausing/resuming setinterval() and not reset it

Actually i am not that great with JS but i try to learn and i tried solving my own issue for 2 days but i couldn’t fix it so i am here to ask for help. my problem is i am trying to pause and resume count down timer with setinterval(); and when i use clearinterval(); it reset it when i recall setinterval(); again. here is my code:

[CODE]<script type=’text/javascript’>
document.getElementById(‘myVideo’).addEventListener(‘playing’,myHandler,false);
function myHandler(e) {
if(!e) { e = window.event; }

$(“#box”).hide();

var replay = document.getElementById(“replay”);
var container = document.getElementById(‘dl’);
var seconds = 10;
var timer;
var isPaused = false;

function countdown() {
seconds–;

if(seconds > 0 && !myVideo.paused) {
isPaused = false;

if(!isPaused) {

container.innerHTML = ‘<font color=”black”> You can Skip the Ad after <b>’+seconds+'</b> seconds.. </font>’;

}
} else if (seconds > 0 && myVideo.paused)
{
isPaused = true;
clearInterval(timer);
}else {

$(“#dl”).hide();
$(“#MyButton”).css({
‘cursor’:’pointer’,
‘display’:’block’})
$(“#replay”).css({
‘cursor’:’pointer’,
‘display’:’block’,
‘background-color’:’#ffffff’,
‘color’:’#3399ff’,
‘border’:’2px solid #ffffff’,
‘border-radius’ : ’25px’
})
clearInterval(timer);
}
}
timer = window.setInterval(countdown, 1000);
}

</script>
[/CODE]

it works when i pause it but when i play vid again the timer count down from the start (10) and when i remove the clearinterval(); that inside

[CODE]else if (seconds > 0 && myVideo.paused)
{
isPaused = true;
clearInterval(timer);
}[/CODE]

this conditional, it actually kinda work by continue previous count down but bring with it new count down so it like go back and forth between paused second and new one.

what i need to accomplish from this code briefly:

1- when video first time plays which is when the page loads for first time the count down timer begins from (0secs)

2- if user paused the video the count down pause as well with the video.

3- when user play again the video after the pause the count down timer continue counting from second the user did paused at and not from begining.

4- restart back by counting down new 10 seconds when clicking replay button (this replay button don’t show up except when 10 seconds end tho).

point 1,2 and 4 already work in the code i provided above but my all problem is number 3 which is when i play the video again after a pause the count down begins counting from 10 if i include a clearInterval(); in condition of video.paused(); or if i didnt include clearInterval(); it will continue counting down from second i paused from but begining new one from 10 and timer keeps swinging between continued second and new one… if i only can stop new timer from begining it will be great and thats all i want and missing for me.

thats all and hopefully i get help from someone soon

Yours,
Maxwel

to post a comment
JavaScript

26 Comments(s)

Copy linkTweet thisAlerts:
@deathshadowAug 07.2014 — When you clear it, it stops existing -- you never set it again... when you unpause, you have to do a:

timer = window.setInterval(countdown, 1000);

Again.

It's hard to say much more about your problem without seeing the markup being manipulated, but it might help if you didn't set CSS from the markup, had code formatting that made the least bit of sense, weren't using innerHTML to put tags like FONT into the page that have no business on any site written after 1997, and it also might not be a bad idea. You also don't have to say "VAR" multiple times if making multiple VAR in a row, you can comma delimit them instead.

I'd also NOT do a decrement on your seconds until I knew the state of the value... and I'd probably axe the jQuery that's not doing a blasted thing for you other than encouraging bad coding habits.

Again though, I'd have to see more of the big picture to provide real help -- I also have the feeling you omitted some scripting as there's a lot of handler stuff on which this should be reliant that I'm not seeing.

But again, that's why snippets suck. It's like doing brain surgery through a keyhole without an endoscope.
Copy linkTweet thisAlerts:
@MaxwelauthorAug 07.2014 — hey deathshadow,

At first, i want to thank you cuzi really learnt much from ur above post and will clean up my code by following what u mentioned above and i am glad that there are ppl out there love to help like you. ? (gonna book mark this thread cuz of ur above post for later too)

Secondly, do u mind pming the code instead? cuz i wont be able to post it all here


Thanks again,

Maxwel
Copy linkTweet thisAlerts:
@deathshadowAug 07.2014 — No problem if you want to PM it, but you may have to link, the PM system here is limited to 2k messages. ?

[i]With a rather tiny maximum box size as I've also discovered to my dismay[/i]
Copy linkTweet thisAlerts:
@rootAug 07.2014 — IMHO either use a JQuery or similar framework and ask in the JavaScript frameworks forum for help or just use JavaScript itself.

When using time elements you should use time itself and not attempt to track time with a variable, any number of bottlenecks in a system can cause overheads that then cause a script to lag, even with the best system, you will find that your browser has some lag because of hooking elements and creating events all take time which can mean a small difference in what you start with on countdown

Example...

[CODE]<div id="time"></div>
<script>
target = document.getElementById("time");
endTime = new Date().getTime() + 30000; // 30 sec's in ms

function update(){
t=new Date().getTime(); // time reference NOW!
s = Math.floor( (endTime - t) / 1000); // how much time left
if( t > endTime ) clearInterval(x);
else target.innerHTML = s + " Sec.";
}

x = setInterval("update()",1000);
</script>[/CODE]
Copy linkTweet thisAlerts:
@deathshadowAug 07.2014 — ~. so your answer to overhead and memory issues is to throw more code at it? Especially the slow and overhead-wasting time function and complex math? AND the ridiculous bloated overhead of the fat bloated idiotic "framework" while at it?!?

That makes sense.

... also doesn't address starting and stopping based on the video's status, which is the OP's question... which using your method the handler for starting/stopping would have to recreate endTime in addition to calling setInterval again.

Well, unless one were to just allow setInterval to run and not do anything while the video is paused... As much of a "waste" of processing time as it might be, it might be the smoother way of handling it.
Copy linkTweet thisAlerts:
@MaxwelauthorAug 09.2014 — Idk how to pm u! I can't find any PM button on your profile! Any idea?

Sorry for late reply but had rl tasks here

Thanks alot for accepting me to pm you and for all the help,

Maxwel
Copy linkTweet thisAlerts:
@rootAug 09.2014 — ~. so your answer to overhead and memory issues is to throw more code at it? Especially the slow and overhead-wasting time function and complex math? AND the ridiculous bloated overhead of the fat bloated idiotic "framework" while at it?!?

That makes sense.

... also doesn't address starting and stopping based on the video's status, which is the OP's question... which using your method the handler for starting/stopping would have to recreate endTime in addition to calling setInterval again.

Well, unless one were to just allow setInterval to run and not do anything while the video is paused... As much of a "waste" of processing time as it might be, it might be the smoother way of handling it.[/QUOTE]


setInterval is only set once as is the endtime, for the OP and their query about pausing, theirs no point in pausing a countdown that is limiting the playback of a video if the person has to wait 30 seconds.

I am making a big assumption here that what the OP really wants is a bypass of some sort for people who have either subscribed or paid for immediate access.

Each time the function is called, the only recalculation is the time remaining and if it has expired, the interval timer is canceled.

With a bit of modification, the code could initiate play() feature of the video that is being timed out.

As for the scathing comment from yourself, what are you proposing? all you have done so far is criticize the OP and my offering of a possible resolution to the problem.

Perhaps you should stop criticizing other people and if you feel that you can contribute, post, otherwise keep your thoughts to yourself and butt out because the more you keep this up, the more of a tool you are becoming.
Copy linkTweet thisAlerts:
@MaxwelauthorAug 09.2014 — guys i am simply trying to do something like youtube ads system. so i want when the user pause the vid the countdown timer pause as well and when he press play again it continue the count down from where he paused not from the begining ? thats simply what i am trying to do with this JS code
Copy linkTweet thisAlerts:
@rootAug 09.2014 — If you use HTML5 and the <video> tag, you can gather stream information like time position and also seek to times, perhaps if you were more clear about your intentions then your answer would have come quicker. TBH I have never seen ads on youtube, so I don't know how they operate.
Copy linkTweet thisAlerts:
@MaxwelauthorAug 09.2014 — @. Thanks alot but thats not what i want still what i want is to be able to pause and continue countdown timer from where i paused it. its not anything related to video or its playback. this count down timer is completely seperate from video and its position.

Thanks alot again for all the help,

Maxwel
Copy linkTweet thisAlerts:
@deathshadowAug 10.2014 — I'm getting what you're asking, that's why I suggested simply letting the timer update run, but not update while video.paused is true.

Something like:

function countdown() {
if (myVideo.paused) return;
if (!myVideo.ended) {
if (seconds--) {
container.innerHTML = 'You can skip the ad after ' + seconds + ' seconds.';
return;
}
container.innerHTML = 'Put your skip link here';
}
clearInterval(timer);
}


Using return to short-circuit our way out reduces the total code and the overhead slightly. You pause the video element, just let the timer run rather than play with it -- one interval every second isn't going to break the bank. Seconds hits 0, show the advert. Remember, 0 is the same as false during a loose compare, so you can decrement and check all-in-one.

That's really all you're trying to do there, right? Count down showing how long before they can skip what I assume is an advert, then replace the skip text with the link to skip, halting the countdown if the advert ends, the timer ends, and not doing anything if the video is paused.

Leaving it running means you don't have to hook your video's play button to resume the counter.
Copy linkTweet thisAlerts:
@deathshadowAug 10.2014 — I am making a big assumption here that what the OP really wants is a bypass of some sort for people who have either subscribed or paid for immediate access.[/quote]
That's NOT what's being asked. So you've basically never used youtube? I understood the question, I just need to see a HELL of a lot more of the OP's code to even try and offer a realistic solution and ways to fix what is -- to be frank -- a hell of a lot of bad code.

As for the scathing comment from yourself, what are you proposing? all you have done so far is criticize the OP and my offering of a possible resolution to the problem.[/QUOTE]
I asked for clarification AND said a possible solution, which I just elaborated on.

As to your "offering" it has not one thing to do with what they were asking -- hence the NEED for clarification.
Copy linkTweet thisAlerts:
@MaxwelauthorAug 10.2014 — hey Deathshadow,

Thanks for all the help and support and yes u got me this time right and i changed my code to look like that:

[CODE]var replay = document.getElementById("replay");

var container = document.getElementById('dl');
var seconds = 10;
var timer;
var isPaused = false;


function countdown() {

if (myVideo.paused){ return;
}
if (!myVideo.ended) {
if (seconds--) {


container.innerHTML = '<font color="black"> You can Skip the Ad after <b>'+seconds+'</b> seconds.. </font>';
return;
}


$("#dl").hide();
$("#MyButton").css({
'cursor':'pointer',
'display':'block'})

$("#replay").css({
'cursor':'pointer',
'display':'block',
'background-color':'#ffffff',
'color':'#3399ff',
'border':'2px solid #ffffff',
'border-radius' : '25px'
})
}
clearInterval(timer);
}
timer = window.setInterval(countdown, 1000);
}
[/CODE]


my play pause js script is as simple as myVid.play(); and myVid.pause();

but the problem is that when i pause the video then replay it the counter begin new count down and keep going back and forth between old and new one which was same issue i had with me other code. any suggestions?
Copy linkTweet thisAlerts:
@deathshadowAug 11.2014 — I'd have to see more of that code, but it looks like you're setting it again after the clear... which you do NOT want to do.

Side note, you don't need to say VAR so much as you can comma delimit them, if you're only doing a return don't waste time with extra {} around it.... some indentation that makes sense would help, and I REALLY suggest axing that jQuery nonsense and playing games with the CSS from the scripting. That's NOT good coding practices. (gee, jQuery promoting sleazy / bad practices, who knew?). This is also 2014 not 1998, STOP USING THE BLASTED FONT TAG. Likewise time is not a proper name or book title, why are you putting <b> around it?

You're also missing some semi-colons.

AHA, in formatting it, you've got the clearInterval [b]AFTER[/b] the function instead of inside it. It needs to be swapped with the } before it. Goes next to that jQuery-tardery, not after the }

Here it is formatted and cleaned up, with that swap made.

var
replay = document.getElementById("replay"),
container = document.getElementById('dl'),
seconds = 10,
timer;

<i> </i> function countdown() {
<i> </i> if (myVideo.paused) return;
<i> </i> if ((!myVideo.ended) &amp;&amp; (seconds--)) {
<i> </i> container.innerHTML = 'You can Skip the Ad after &lt;span&gt;'+seconds+'&lt;/span&gt; seconds...';
<i> </i> return;
<i> </i> }
<i> </i> $("#dl").hide();
<i> </i> $("#MyButton").css({
<i> </i> 'cursor':'pointer',
<i> </i> 'display':'block'
<i> </i> });
<i> </i> $("#replay").css({
<i> </i> 'cursor':'pointer',
<i> </i> 'display':'block',
<i> </i> 'background-color':'#ffffff',
<i> </i> 'color':'#3399ff',
<i> </i> 'border':'2px solid #ffffff',
<i> </i> 'border-radius' : '25px'
<i> </i> });
<i> </i> clearInterval(timer);
<i> </i> }
<i> </i>}
<i> </i>timer = window.setInterval(countdown, 1000);
}


If you don't clear it when it ends, it will keep trying to run over and over... Though I'm not sure why the count would start over unless this is in some function you are calling unnecessarily on resume. Given the number of closing { I'm assuming that's the case, which is why I need to see ALL of it, not just a snippet to advise further.

Though really I'd have THREE outcomes, not two. the countdown, the skip link, video ended.
Copy linkTweet thisAlerts:
@MaxwelauthorAug 11.2014 — hey deathshadow,

i really appreciate all the help and support u offer and i am sorry for bothering much but here is the whole JS concerning the count down timer. if u want me to provide whole php script i will do but i donno how to pm u through forums here. i can't see any pm button to be able to do that.

i tried ur script but it still go back and forth between old and new one when i stop then resume the video like it used to do before. maybe cuz adding the playing eventlistener? idk. i was about to clean my whole code according to ur first post but after i get this working first.

[CODE]<script type='text/javascript'>

document.getElementById('myVideo').addEventListener('playing',myHandler,false);

function myHandler(e) {
if(!e) { e = window.event; }

$("#box").hide();
$("#pause").show();
$("#clickhere").hide();

var
replay = document.getElementById("replay"),
container = document.getElementById('dl'),
seconds = 10,
timer;

function countdown() {
if (myVideo.paused) return;
if ((!myVideo.ended) && (seconds--)) {
container.innerHTML = 'You can Skip the Ad after <span>'+seconds+'</span> seconds...';
return;
}
$("#dl").hide();
$("#MyButton").css({
'cursor':'pointer',
'display':'block'
});
$("#replay").css({
'cursor':'pointer',
'display':'block',
'background-color':'#ffffff',
'color':'#3399ff',
'border':'2px solid #ffffff',
'border-radius' : '25px'
});
clearInterval(timer);
}
timer = window.setInterval(countdown, 1000);
}


</script>[/CODE]


Play/pause code:

[CODE]<script type='text/javascript'>


function play() {
if (myVideo.paused){
myVideo.play();
$("#play").hide();
$("#pause").show();

}}

function pause() {
if (!myVideo.paused){
myVideo.pause();
$("#pause").hide();
$("#play").show();
}}

</script>[/CODE]


i wish this time the codes that i post make more sense and i wish i get this working ? cuz it took too long and still not :/


Thanks in advance.

Maxwel
Copy linkTweet thisAlerts:
@deathshadowAug 11.2014 — Ok, you have it inside myHandler instead of outside it. EVERY time you call 'myhandler' it's going to reset it. It needs to be independent of that parent function to work 'properly'... this also seems like a good candidate for an anonymous function to isolate the scope of this.

&lt;script type="text/javascript"&gt;&lt;!--

(function(d) {

<i> </i>var
<i> </i> replay = d.getElementById('replay'),
<i> </i> container = d.getElementById('dl'),
<i> </i> myVideo = d.getElementById('myVideo'),
<i> </i> seconds = 10,
<i> </i> timer = false;

<i> </i>function eventAdd(e, event, handler) {
<i> </i> if (e.addEventListener) e.addEventListener(event, handler, false);
<i> </i> else e.attachEvent('on' + event, handler);
<i> </i>}

<i> </i>function countdown() {
<i> </i> if (myVideo.paused) return;
<i> </i> if ((!myVideo.ended) &amp;&amp; (seconds--)) {
<i> </i> container.innerHTML = 'You can Skip the Ad after &lt;span&gt;'+seconds+'&lt;/span&gt; seconds...';
<i> </i> return;
<i> </i> }
<i> </i> $("#dl").hide();
<i> </i> $("#MyButton").css({
<i> </i> 'cursor':'pointer',
<i> </i> 'display':'block'
<i> </i> });
<i> </i> $("#replay").css({
<i> </i> 'cursor':'pointer',
<i> </i> 'display':'block',
<i> </i> 'background-color':'#ffffff',
<i> </i> 'color':'#3399ff',
<i> </i> 'border':'2px solid #ffffff',
<i> </i> 'border-radius' : '25px'
<i> </i> });
<i> </i> clearInterval(timer);
<i> </i> timer = false;
<i> </i>}

<i> </i>eventAdd(myVideo, 'playing', function(e) {
<i> </i> $("#box").hide();
<i> </i> $("#pause").show();
<i> </i> $("#clickhere").hide();
<i> </i> if (timer !== false) timer = window.setInterval(countdown, 1000);
<i> </i>});

})(document);

--&gt;&lt;/script&gt;


Though still I really need to see the markup this is playing with to say more. I think a lot of the jQuery garbage you're doing here could be replaced with a single class swap and letting CSS do most of the heavy lifting on your player controls.
Copy linkTweet thisAlerts:
@MaxwelauthorAug 11.2014 — Hey bro,

I really appreciate all u time and help but the code u provided me dont work. it dont even show the count down or the skip link.

here is the code:

[CODE]<script type="text/javascript">

(function(d) {

var
replay = d.getElementById('replay'),
container = d.getElementById('dl'),
myVideo = d.getElementById('myVideo'),
seconds = 10,
timer = false;

function eventAdd(e, event, handler) {
if (e.addEventListener) e.addEventListener(event, handler, false);
else e.attachEvent('on' + event, handler);
}

function countdown() {
if (myVideo.paused) return;
if ((!myVideo.ended) && (seconds--)) {
container.innerHTML = 'You can Skip the Ad after <span>'+seconds+'</span> seconds...';
return;
}
$("#dl").hide();
$("#MyButton").css({
'cursor':'pointer',
'display':'block'
});
$("#replay").css({
'cursor':'pointer',
'display':'block',
'background-color':'#ffffff',
'color':'#3399ff',
'border':'2px solid #ffffff',
'border-radius' : '25px'
});
clearInterval(timer);
timer = false;
}

eventAdd(myVideo, 'playing', function(e) {
$("#box").hide();
$("#pause").show();
$("#clickhere").hide();
if (timer !== false) timer = window.setInterval(countdown, 1000);
});

})(document);

</script>[/CODE]



I can't really pm u through webdeveloper.com so if u dont mind me sending to u whole code through an email u can send me ur email to my email "[email protected]" and i will send u the whole code to urs ?.


i have some questions if u don't u told me to stop using jquery so what i can use instead? also aint those <!-- --> are html commenting tags why u used them in above post?how we can check for "seconds--" if we are not decrementing the seconds before we check for it? can u explain for me these three parts "function eventAdd(e, event, handler), e.attachEvent('on' + event, handler); , function(d)" and why u used "d" in "function(d)" ?

maybe these are dumb question but i try to learn more ?. also what are the strings that added in brackets that after any function? what are they useful for? cuz sometimes they are declared before the function and sometimes they are never declared and still i can see the pc get it.

i wish i was clear in my questions and don't bother ya by asking them but i am really curious and want to know and learn. u can link me with tutorials if that can be easier for u to answer any of the questions above but please try to answer simple ones urself cuz i am sure it's gonna be easier and clear to understand.

Thanks in advance

Maxwel
Copy linkTweet thisAlerts:
@deathshadowAug 12.2014 — i have some questions if u don't u told me to stop using jquery so what i can use instead?[/quote]
Normal javascript without the bloated framework. Most of the time it's the same or less code on your part, and it's always less code overall.

also aint those <!-- --> are html commenting tags why u used them in above post?[/quote]
So that browsers with scripting disabled, unavailable or unknown won't show the source code of the script in the middle of the page.

http://www.w3.org/TR/html4/interact/scripts.html#h-18.3.2

They put a leading // when there's not a single JS engine in circulation that needs it as the HTML parser strips the --> long before it gets to the point of running scripting.

how we can check for "seconds--" if we are not decrementing the seconds before we check for it?[/quote]
Much like in C, all operations will return their value for evaluation, even variable assignments.

var a = 10;

console.log(--a);

console.log(a--);

console.log(a);

Will output 9, 9 and 8. Confused?

--a performs the decrement BEFORE evaluating the value. 10-1 == 9, so it outputs 9. a-- performs the decrement AFTER evaluating the value. So it's 9, then it subtracts 1... making the last one output 8. Depending on the language or even the processor one or the other could be faster... (real fun).

In this case "seconds--" evaluates the value, if it's zero that's treated as false. otherwise it's true... then it's decremented. On false we kill the timer so it doesn't go negative.

so:
if (seconds--) {
// do something
}


kind of the same as saying:

if (seconds) {
seconds--;
// do something
} else seconds--;


Though not exactly... that's a gross oversimplification.

function eventAdd(e, event, handler), e.attachEvent('on' + event, handler);[/quote]
That's a polyfill -- it's just a simple helper function to make it so you can transparently add events in Modern Browsers, and IE. Everything except IE uses "addEventListener", which uses "attachEvent" instead. You have to remember that when Microsoft first implemented "JScript" it's called "JScript" and NOT "JavaScript" for a reason, they were worried about being sued by Nyetscape, so they created their own version with enough 'differences' to sqeak through. Honestly it's a miracle ANY scripting in IE is compatible with "rest of world".

In either case those methods mean that if other scripts want to attach their own events, they won't conflict with each-other like using [i]Element[/i].on[i]event[/i] would -- or worse the stupid malfing on[i]event[/i] HTML attributes that IMHO should be removed from the HTML specification.

function(d)" and why u used "d" in "function(d)" ?[/quote]
That's an anonymous function -- a function with no name that in this case is self instancing.

A simple example:

(function(a) {
alert(a);
})('test');


Would alert 'test'. NONE of the values inside that function exist in the global scope, meaning there's little to no risk of variables or functions inside it accidentally conflicting with other scripts.

There's some noodle-doodle BS circulating about anonymous functions on how they've got this "massive" memory overhead -- they only do so if you are going to call it more than once as every time you pass an anonymous function by reference you're making a new copy. For example:

for (t = 0; t &lt; labels.length; t++) {
eventAdd(labels[t], 'click', function(e) { alert(e); });
}


Would create a separate function for each of those labels -- which IS a waste of memory. In that scenario you are better off doing:

<i>
</i>function clickLabel(e) { alert(e); }

for (t = 0; t &lt; labels.length; t++) {
eventAdd(labels[t], 'click', clickLabel });
}


Which would lower the memory footprint of the program.

But if the function is only ever going to exist once, there's NO legitimate reason not to use them, particularly as 'scope isolators' / namespaces. It's one of those cases where people turn one little tiny corner-case where it's a problem into ignorant "NEVER USE IT" nonsense. Same as the people who say "never use tables" or "always use STRONG and EM instead of B and I" -- which is also a bunch of halfwit nonsense spouted by people who don't know enough on the topic to be flapping their gums.

In any case, look at the opening and closing of that anonymous function (which is behaving as what PHP folks would call a singleton).

function(d) {
})(document);


So basically d == document. So we can say d.getElementsById instead of document.getElementsById. It's a petty way to save a few bytes, but it also creates a 'local scope' reference to document that thanks to how variables are looked up by most JavaScript engines, means it's able to be found faster.

Picked up that trick from some of Google's code embeds for things like G+ likes. Good enough for Google it can't be that bad.

also what are the strings that added in brackets that after any function? what are they useful for? cuz sometimes they are declared before the function and sometimes they are never declared and still i can see the pc get it.
[/quote]

Not sure what you mean by that. Could you elaborate what you're referring to there?
Copy linkTweet thisAlerts:
@MaxwelauthorAug 13.2014 — nvm about the last question cuz u already answered it in ur previous answer. Also, i am sooo happy cuz today i learnt much about js from u and things began to get more easier and clear for me ?. appreciate it so much and really happy ? and through this topic and reading ur posts i learnt much in how i write better code and clean and how to save memo plus clarification of things i wanted to know much about js so thanks alot ?

Also, i sent to ya the whole file to ur email and waiting ur reply whenever u can ?

Yours,

Maxwel
Copy linkTweet thisAlerts:
@deathshadowAug 13.2014 — Well, looking at the full thing, I'm ending up with more questions than answers -- like why are you forcing their second and third visits to the page to auto-refresh via HTTP with 0 waits? That's a unnecessary strain on the server for ... well, I've no clue why. I'm really not grasping what it is you are doing with counting the visits by IP, all you seem to have is broken annoying refreshes for christmas only knows what.

Next you've got a section doing browser sniffing to serve two different copies of what SEEMS to be the same page... Browser sniffing is ALWAYS a steaming pile of /FAIL/ so I'd swing an axe at that as there's NO legitimate reason to be doing that... which would reduce the size of your php 60% or so.

A big "problem" that's making it hard to work with is that you've just got too much stuff in the markup that should be in external files -- like the CSS and Scripting. Get those into external files so they can be cached, so PHP doesn't have to work as hard parsing all that output, and so it's easier to edit as you have them all in nice neat separate locations.

The markup itself is... ouch. You've got a slew of tags and attributes like CENTER, FONT, BGCOLOR and so forth that have no business on any website written after 1998. You've got a H3 when you don't even have H1 or H2 before it so the heading orders are structural gibberish, you seem to be building massive strings for some sort of random output when the only difference betwixt them would be the value in the FILE attribute and SOURCE tags... etc, etc...

Much less it's using the outdated/outmoded mysql_ functions, something that really was supposed to go the way of the dodo eight years ago, and that they finally added [url=http://php.net/manual/en/function.mysql-connect.php]giant red warning boxes to the manual[/url] waving people off from using as they're going away soon.

I'll ... dig deeper to see if I can make sense of what you're trying to accomplish... I think the first step is going to be dragging the markup into the light and swinging an axe at most of your PHP that isn't actually doing anything that should be done.
Copy linkTweet thisAlerts:
@deathshadowAug 13.2014 — OH, you're also declaring BOTH UTF-8 by the HTML 5 way, and ISO-8859-1 via the META way... PICK ONE, not both.
Copy linkTweet thisAlerts:
@MaxwelauthorAug 13.2014 — hey again,

firstly, i would like to thanks u for helping me and answering my questions and apologize for how messy is my code but i try to learn every day how to code a neat and well coded php/js codes ?.

secondly, i actually refresh the page in the 2nd/3rd visit after i set their count number to 0 to make sure they dont directed to the link before they watch the ads vid. i know it dont make much sense but i am not sure why i did it that way much. i feel dumb :S

secondly, i have read latest post and that made me want ask few question if u dont mind:

1- what is the difference between UTF-8 by the HTML 5 way, and ISO-8859-1 via the META way?

2- what i can do instead of checking browser type then display code that suits it tho?

3- do u want me to use css instead of attributes like CENTER, FONT, BGCOLOR, etc?

4- I never knew mysql_ functions that i use are outdated/outmoded, so where i can find new funcs?

Thanks alot for everything and apologizes for asking too much

Yours,

Maxwel
Copy linkTweet thisAlerts:
@MaxwelauthorAug 14.2014 — Hey again,

sorry for posting another post but i can find the edit button and i was wondering if it is possible to detect each computer behind same ip? like how i can differentiate between a pc and another behind same ip? is there a way to get port number or some local ip to achieve that task?

also i have another question is that i realized that this forum keep me logged even if my router restarted and my ip changed how is that accomplished as well

Thanks again so so much.

Yours,

Maxwel
Copy linkTweet thisAlerts:
@deathshadowAug 14.2014 — secondly, i actually refresh the page in the 2nd/3rd visit after i set their count number to 0 to make sure they dont directed to the link before they watch the ads vid. i know it dont make much sense but i am not sure why i did it that way much. i feel dumb :S[/quote]
Still not following you on that...

1- what is the difference between UTF-8 by the HTML 5 way, and ISO-8859-1 via the META way?[/quote]
They both do the same thing, declare the character set of the document -- the problem is they are two different values for the same information; that's like saying the language is English and then saying it's Portuguese -- which is it? NOT that it really matters as the mime-type sent by the server trumps those values, but it's still confusing to have both the new and old declarations declaring different values for the same field.

2- what i can do instead of checking browser type then display code that suits it tho?[/quote]
Use code that works in all of them... I'm not even sure what 'difference' you'd have that warrants wasting that much code on browser sniffing as I'm not even seeing anything different enough in the markup between your two 'versions' to warrant it.

Though if you had a well formed HTML to begin with...

3- do u want me to use css instead of attributes like CENTER, FONT, BGCOLOR, etc?[/quote]
Pretty much, and that CSS belongs in an external stylesheet, [b]NOT[/b] in the markup. HTML is for saying what things ARE, [b]NOT[/b] what they look like. As such, those [b]vendor specific[/b] tags that were added during the browser wars over a decade and a half ago have no business in the HTML; [i]and to be brutally frank, they NEVER did![/i]

4- I never knew mysql_ functions that i use are outdated/outmoded, so where i can find new funcs?[/quote]

I would suggest that you use PDO. It's not that different even though it's object driven, and lets you use multiple SQL engines and not just mySQL. (though you can still use it if desired).

http://php.net/manual/en/book.pdo.php

The big thing there is "prepared queries" which auto-sanitizes values (no more escapestring nonsense), can be re-used with different data, and a whole host of other advantages. The other alternative is mysqli -- which I dislike for a variety of reasons.

For example where in your code you have:
mysql_connect("", "", "") or die(mysql_error());
mysql_select_db("") or die(mysql_error());

$result = mysql_query("SELECT * FROM name WHERE ip = '$client_ip'")
or die(mysql_error());

$row = mysql_fetch_array($result);

[i]troublesome since it has no query failure handling...[/i]

If I wrote that as PDO it would go:
$db = new PDO(
'mysql:host=localhost;dbname=database',
'username',
'password'
);

$statement = $db-&gt;prepare('
SELECT *
FROM name
WHERE ip = :ip
');

$statement-&gt;execute([':ip' =&gt; $client_ip]);

if ($row = $statement-&gt;fetch('PDO::FETCH_ASSOC')) {


the first string passed to 'new PDO' is called a "data source name" or "PDN" for short. The first word before the colon says which database engine to use, the host says what host to use (like 127.0.0.1 or localhost), dbname is the database you are connecting to, so whatever you put as the = is equivalent to mysql_db_select's value.

The PDO::prepare method returns a PDOStatement on which you can pass values in an array with the PDOStatement::execute method. Putting a : before a name creates the identifier to match in the array.

Not too tough.

i was wondering if it is possible to detect each computer behind same ip? like how i can differentiate between a pc and another behind same ip? is there a way to get port number or some local ip to achieve that task?[/QUOTE]

That question makes me almost understand what you were doing with the IP and the database and so forth, and why it made NO sense to me whatsoever. You're unaware of what "sessions" are.

Forums and the like use SESSIONS, a method of storing data server-side based on a single cookie. A unique cookie typically called PHPSESSID is created and sent ot the browser, which in return passes it back with every file request. That ID is then used to pull information from a database automatically. you can store all sorts of information in the session -- like the user's database ID and it is kept server-side for the length of the 'session' while never sending that information client-side.

You start a session with:

session_start();

at the start of any user-callable file you want to use sessions in. It will either continue the existing session, or create one if none exists. I usually suggest you then immediately call:

session_regenerate_id();

Which will create a new random session ID. Doing this takes a bit of extra overhead, but reduces the odds of what's called a "main in the middle" attack where someone takes that same cookie value and tries to fake it.

You can then test if a value exists in the session and what it's value is:

if (
isset($_SESSION['test']) &amp;&amp;
($_SESSION['test'] == 1)
) {


Or you could set it's value thus:

$_SESSION['test'] = true;

Because they're cookie driven, the IP address doesn't even play into it. That's how 99.99% of forums, blogs or other sites that have logins... handle tracking if a user is logged in.

Though I like to store and compare the UA string and IP address in the session for comparison, and rejecting the session if those change as another way of fighting 'man in the middle' attacks. Mind you those are just as easy to fake, but it's like door-locks on a car -- it keeps the 'honest' people out.

The nice part about PHP sessions is they take the 'grunt work' out of calling the database if all you are doing is tracking a visitor for the time of their visit when there's no corresponding login system or login required.
Copy linkTweet thisAlerts:
@MaxwelauthorAug 17.2014 — hey again, Thanks for the million time for answering my questions and i really appreciate it and sorry for late/delay reply but i couldnt get on pc for rl situations.

1- I know about sessions but i never knew it can work without login system?! how is that done even tho?

2- i didn't get about that part much "I like to store and compare the UA string and IP address in the session for comparison, and rejecting the session if those change as another way of fighting 'man in the middle' attacks". so can u explain it more detailed and easy way cuz it seems so important to help in preventing hacking ur login systems. hence, the website so will be great of u to explain it please for me deeper but easier ?

3- any news about my script? did u get the point out of it yet? how how i can make that count down work without beginning from first every time user pause then play the video?


Thanks for everything once again and sorry if i cause any disturbance or inconvenience by asking those questions but i really try to learn and hopefully when others who search for something u mentioned before they get things more clear and helpful as well ?

Yours,

Maxwel
Copy linkTweet thisAlerts:
@MaxwelauthorSep 01.2014 — i don't know why my posts dont show anymore? is there any issues with them?

Thanks in advance

Maxwel

  • - reply -> As a "newbie" all your posts are moderated, so there may be a delay before they become visible on the site. If a post is trivial it may be deleted, so not become visible at all. If a moderator has more concerns with your posts, they will generally contact you.


  • jedaisoul.
    ×

    Success!

    Help @Maxwel spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 6.13,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @meenaratha,
    tipped: article
    amount: 1000 SATS,

    tipper: @meenaratha,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,
    )...