I am working on the following code for a chrome extension. Basically I want it to check the page that initially loads and if it matches my website st.mywebsite.com it will execute the code. Right now it doesn't check and will execute any pages that loads. I am trying to get it to load http://st.mywebsite.com/?q= plus the terms in the array. So every X number of seconds/minutes it will load a new term in the array and add it to the url http://st.mywebsite.com/?q=can anyone help?
if((window.location.hostname != "st.mywebsite.com")){
window.onload = function() {
terms = new Array("5d65sd", "95sd4s", "h2j4g8h", "c87e2dd", "e6e5f2g4", "3m5g5gv");
min = 1;//minimum
max = 60;//maximum
randomnumber = Math.floor(Math.random() * (max - min + 1)) + min;
var seconds = randomnumber;
var timer;
function countdown() {
var container = document.getElementById('right');
seconds--;
if(seconds > 0) {
container.innerHTML = '<p>Please wait <b>'+seconds+'</b> seconds.</p>';
} else {
window.location = 'http://st.mywebsite.com/?q='+terms;
}
}
timer = setInterval(countdown, 1000);
}
}
At the line you have window.location, change it to window.location.href
Related
I am trying to do a simple redirect after x seconds on a page with a countdown timer. Every time I call the function I want the timer to be reset, however when i call it a second or third time the timer seems to have 3 different countdowns. Can anyone see why this is?
function delayRedirect(){
document.getElementById('countDown').innerHTML = 'Session Timeout In: <span id="countTimer"></span> seconds....';
clearInterval(sessionTimer);
var sessionTimer = null;
var timeleft = 60;
var sessionTimer = setInterval(function(){
timeleft--;
document.getElementById('countTimer').innerHTML = timeleft;
if(timeleft <= 0)
clearInterval(sessionTimer);
returnToLogin();
},1000);
}
Put the sessionTimer globally. What you currently do is re-declare sessionTimer every time you enter delayRedirect.
Working example:
const but = document.getElementById("but");
but.addEventListener("click", delayRedirect);
//define it globally
var sessionTimer = -1;
function delayRedirect() {
//clear it if it previously exists
clearInterval(sessionTimer);
sessionTimer = setInterval(function() {
console.log("sessionTimer " + sessionTimer);
}, 1000);
}
<button id="but">Run</button>
I feel like all the answers only address the Y part, not the X part, given that this is clearly an XY problem.
While the solution is to use a variable that isn't local to the function, solving the actual problem doesn't require clearing anything. One can simply use an interval to tick down, and reset the count to delay the redirect:
var timeleft = 60;
setInterval(function() {
if (--timeleft === 0) returnToLogin();
countTimer.innerHTML = timeleft;
}, 1000);
delay.onclick = function() {
timeleft = 60;
}
function returnToLogin() {
console.log("returning to login");
}
<p>Session Timeout In: <span id="countTimer">60</span> seconds....</p>
<button id="delay">Delay</button>
so I seem to be having some real logic errors amidst my timer here, and I'm not quite sure how to fix them. I've made the code somewhat work, but I know for a fact there's a handful of logical errors, and I honestly have been working on it for a few days intermittently and can't seem to get it solved. Based on the code I've laid out you can pretty much understand my thinking of how I want to tackle this issue. I understand this isn't best practice, but I am just trying to work on my problem solving on these issues! Any help is greatly appreciated. I really need the most help on figuring out how to configure the Pause and Play functions with my given timer functionality. (Please no jQuery examples only raw JS)
// Necessary Variables for the program
let timer = document.querySelector(".time");
let button = document.querySelector("#btn");
let subtractBreak = document.querySelector("#subtractBreak");
let addBreak = document.querySelector("#addBreak");
let subtractSession = document.querySelector("#subtractSesssion");
let addSession= document.querySelector("#addSession");
// Keeping up with the current count of the break and session
let currentCount = document.getElementsByClassName("counterNum");
// Keeps up with all the buttons on session and break +/-
let counterBtn = document.getElementsByClassName("counterBtn");
// Pause and play Variables
let pause = document.querySelector("#pause");
let play = document.querySelector("#play");
// keeps up with an offsetting count.
let count = 0;
let timerGoing = false;
let sessionTimeLeft = 1500;
let breakTimeLeft = 5;
let timeWhilePaused = sessionTimeLeft;
let paused = false;
function formatTimer(time){
let minutes = Math.floor(time / 60);
let seconds = time % 60;
return `${minutes.toLocaleString(undefined, {minimumIntegerDigits: 2})}:${seconds.toLocaleString(undefined, {minimumIntegerDigits: 2})}`;
}
// This function needs to be fixed - It allows the timer to go negative past 0.
function countdown(){
timerGoing = true;
count++;
timer.innerHTML = formatTimer(sessionTimeLeft - count);
// Used to remove the listener
button.removeEventListener("click", interval);
console.log("Timer is at: " + formatTimer(sessionTimeLeft - count) + "\nCount is at: " + count + "\nsessionTimeLeft = " + sessionTimeLeft);
// Checking if the time of the current session is up
if(count == sessionTimeLeft){
timerGoing = false;
alert("We're here stop...");
startBreak(breakTimeLeft);
}
}
button.addEventListener("click", interval);
function interval(e){
setInterval(countdown, 1000);
console.log("running");
e.preventDefault();
}
/*
I look through the event listener to be sure to check and see if any of them have been hit
not just the first one, which is what it would check for.
*/
for(let i = 0; i < counterBtn.length; i++){
counterBtn[i].addEventListener("click", changeCount);
}
/*
This functions whole job is to see which button was clicked using the 'event target'
Once found it can determine if the id is subtract - then it will subtract the next element
founds' amount, due to the structure of the HTML this will always be the number following;
this process works vice versa for the addition, with the number being the element before.
*/
function changeCount(e){
let clickedButtonsId = e.target.id;
if(timerGoing == false){
if(clickedButtonsId === "subtractBreak"){
let currentValue = e.target.nextElementSibling.innerText;
if(currentValue != 1){
currentValue--;
e.target.nextElementSibling.innerText = currentValue;
breakTimeLeft -= 1;
}
} else if(clickedButtonsId === "subtractSession"){
let currentValue = e.target.nextElementSibling.innerText;
if(currentValue != 1){
currentValue--;
e.target.nextElementSibling.innerText = currentValue;
sessionTimeLeft = currentValue * 60;
// Allows the timer to update in real time
timer.innerHTML = formatTimer(sessionTimeLeft);
}
}
else if(clickedButtonsId === "addBreak"){
let currentValue = e.target.previousElementSibling.innerText;
currentValue++;
e.target.previousElementSibling.innerText = currentValue;
breakTimeLeft += 1;
}
else{
let currentValue = e.target.previousElementSibling.innerText;
currentValue++;
e.target.previousElementSibling.innerText = currentValue;
sessionTimeLeft = currentValue * 60;
// Allows the timer to update in real time
timer.innerHTML = formatTimer(sessionTimeLeft);
}
}
}
/* These functions below are not working */
pause.addEventListener("click", pauseTimer);
function pauseTimer(){
timeWhilePaused = sessionTimeLeft;
button.removeEventListener("click", interval);
console.log("calling pause"+paused+"\n");
paused = true;
console.log("paused after: " + paused);
}
play.addEventListener("click", playTimer);
function playTimer(){
console.log("Paused = " + paused);
if(paused == true){
console.log("calling play");
console.log("Paused = " + paused);
sessionTimeLeft = timeWhilePaused;
setInterval(countdown, 1000);
}
}
function startBreak(time){
console.log("Calling this function");
timer.innerHTML = formatTimer(breakTimeLeft - count);
}
I am trying to display two timer on a webpage with different start times.
First timer only shows for 5 seconds and then after 10 seconds I need to show timer2.
I am very new to Angular and have put together following code.
It seems to be working fine except when the settimeout is called the third time it doesn't work correctly and it starts going very fast.
Controller
// initialise variables
$scope.tickInterval = 1000; //ms
var min ='';
var sec ='';
$scope.ti = 0;
$scope.startTimer1 = function() {
$scope.ti++;
min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
$scope.timer1 = min + ":" + sec;
mytimeout1 = $timeout($scope.startTimer1, $scope.tickInterval); // reset the timer
}
//start timer 1
$scope.startTimer1();
$scope.$watch('timer1',function(){
if($scope.timer1 !=undefined){
if($scope.timer1 =='00:05'){
$timeout.cancel(mytimeout1);
setInterval(function(){
$scope.startTimer2()
$scope.ti = 0;
},1000)
}
}
})
//start timer 2 after 2 mins and 20 seconds
$scope.startTimer2 = function() {
$scope.ti++;
min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
$scope.timer2 = min + ":" + sec;
mytimeout2 = $timeout($scope.startTimer2, $scope.tickInterval);
}
$scope.$watch('timer2',function(){
if($scope.timer2 !=undefined){
if($scope.timer2 =='00:05'){
$timeout.cancel(mytimeout2);
setInterval(function(){
$scope.startTimer1();
$scope.ti = 0;
},1000)
}
}
})
In my view I simply have
<p>{{timer1}}</p>
<p>{{timer2}}</p>
You're basically starting multiple startTimer function so it's adding up. If i understood your problem well you don't even need to have all those watchers and timeouts.
You just can use $interval this way :
$scope.Timer = $interval(function () {
++$scope.tickCount
if ($scope.tickCount <= 5) {
$scope.timer1++
} else {
$scope.timer2++
if ($scope.tickCount >= 10)
$scope.tickCount = 0;
}
}, 1000);
Working fiddle
I wrote a javascript which when used in browser such as chrome, keeps on scrolling such facebook pages in which more content is loaded as you scroll.
i = 0;
minutes = 30;
counter = minutes * 60;
function repeatScroll()
{
console.log('scrolling');
if (i < counter)
{
window.scrollTo(0, document.body.scrollHeight);
i++;
}
setTimeout(repeatScroll, 5000);
}
repeatScroll();
I wanted to do same using phantomjs, but I am unable to do so. I am doubting it has something to do with the delay, but I am unable to figure it out.
This is a snippet from my phantom js code :
var url = "https://www.facebook.com/search/965993006761563/likers";
page.open(url, function (status) {
setTimeout(function () {
page.evaluate(function () {
console.log('gooooooooooooooooo');
});
page.render("liker.png");
page.evaluate(function() {
i = 0;
minutes = 30;
counter = minutes * 60;
function repeatScroll()
{
console.log('scrolling');
if (i < counter)
{
window.scrollTo(0, document.body.scrollHeight);
i++;
}
setTimeout(repeatScroll, 5000);
}
repeatScroll();
});
Console only outputs scrolling once. I am not sure what changes do I need to do.
After scrolling all the way through out I want to extract all profile id's too. Planning to add this just below the above code.
var title = page.evaluate(function() {
var e=document.getElementsByClassName("fsl fwb fcb");
var ids = [];
for(var i = 0 ; i < e.length; i++)
{
ids.push(JSON.parse(e[i].childNodes[0].getAttribute("data-gt")).engagement.eng_tid);
}
console.log(ids);
return ids;
});
Also, when I currently add it, I do not get any profile id output.
Edit : I already read this (How to scroll down with Phantomjs to load dynamic content) but this is not present in my case.
I want to make a countdown timer, that can be used on several places in the same page - so I think it should be a function in some way.
I really want it to be made with jQuery, but I cant quite make it happen with my code. I have e.g. 10 products in a page, that I need to make a countdown timer - when the timer is at 0 I need it to hide the product.
My code is:
$(document).ready(function(){
$(".product").each(function(){
$(function(){
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var count = Seconds_Between_dates;
var elm = $(this).attr('id');
alert(elm);
countdown = setInterval(function(){
$(elm + " .time_left").html(count + " seconds remaining!");
if (count == 0) {
$(this).css('display','none');
}
count--;
}, 1000);
});
});
});
EDIT 1:
$(document).ready(function(){
$(".product").each(function(){
var elm = $(this).attr('id');
$(function(){
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var count = Seconds_Between_dates;
alert(elm);
countdown = setInterval(function(){
$(elm + " .time_left").html(count + " seconds remaining!");
if (count == 0) {
$(this).css('display','none');
}
count--;
}, 1000);
});
});
});
Do you have any solutions to this?
I'd probably use a single interval function that checks all the products. Something like this:
$(function() {
/* set when a product should expire.
hardcoded to 5 seconds from now for demonstration
but this could be different for each product. */
$('.product').each(function() {
$(this).data('expires', (new Date()).getTime() + 5000);
});
var countdown_id = setInterval(function() {
var now = (new Date()).getTime();
$('.product').each(function() {
var expires = $(this).data('expires');
if (expires) {
var seconds_remaining = Math.round((expires-now)/1000);
if (seconds_remaining > 0) {
$('.time-left', this).text(seconds_remaining);
}
else {
$(this).hide();
}
}
});
}, 1000);
});
You could also cancel the interval function when there is nothing left to expire.
Your problem seems to be that this doesn't refer to the current DOM element (from the each), but to window - from setTimeout.
Apart from that, you have an unnecessary domReady wrapper, forgot the # on your id selector, should use cached references and never rely on the timing of setInterval, which can be quite drifting. Use this:
$(document).ready(function(){
$(".product").each(function(){
var end = new Date(/* from something */),
toUpdate = $(".time_left", this);
prod = $(this);
countDown();
function countdown() {
var cur = new Date(),
left = end - cur;
if (left <= 0) {
prod.remove(); // or .hide() or whatever
return;
}
var sec = Math.ceil(left / 1000);
toUpdate.text(sec + " seconds remaining!"); // don't use .html()
setTimeout(countdown, left % 1000);
}
});
});