setTimeout not being fired - javascript

I am using Leaflet to add 3 markers on a floor plan. It works fine. then I tried to let Math.random to produce the coordinates in pixels every 3 secs, remove the old marker and add a new marker. But I found the setTimeout() doesn't work. I tried many solutions, all failed. Please could you guide?
one more question: the control.scale doesn't work either. The scale is still at the bottomleft and ft bar is still there.
I am using Leaflet to add 3 markers on a floor plan. It works fine. then I tried to let Math.random to produce the coordinates in pixels every 3 secs, remove the old marker and add a new marker. But I found the setTimeout() doesn't work. I tried many solutions, all failed. Please could you guide?
one more question: the control.scale doesn't work either. The scale is still at the bottomleft and ft bar is still there.
<script>
var map = L.map('map', {
crs: L.CRS.Simple,
Zoom: 0,
maxZoom:16,
minZoom: -5
});
var bounds = [[0,0], [1079,2159]]; // [y, x]
var image = L.imageOverlay('officemap.jpeg', bounds).addTo(map);
map.setView( [539,1075], 0); // ([y , x] , zoom)
map.fitBounds(bounds);
//L.control.scale('topleft', '50', 'True', 'False', 'True' ).addTo(map); // doesn't work !!!
L.control.scale().addTo(map);
var yx = L.latLng;
var xy = function(x, y) {
if (L.Util.isArray(x)) { // When doing xy([x, y]);
return yx(x[1], x[0]);
}
return yx(y, x); // When doing xy(x, y);
};
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var sol = xy(1079, 539);
//var mizar = xy(2159, 1079);
//var mizar = xy(getRandomIntInclusive(0, 2159), getRandomIntInclusive(0, 1079));
var kruegerZ = xy(0, 0);
var maker_text="I am good!!!";
//var maker_text_array =['Name:', 'Age:', 'Group:'];
L.marker(sol).addTo(map).bindTooltip( 'Sol');
L.marker(kruegerZ).addTo(map).bindTooltip(maker_text);
//var previous_maker=null;
var current_marker=null;
/*
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
};
*/
var i="100";
var mizar = xy(getRandomIntInclusive(0, 2159), getRandomIntInclusive(0, 1079));
current_marker=L.marker(mizar).addTo(map).bindTooltip(i);
function del_add(){
alter("in set");
map.removeLayer(current_marker);
mizar= xy(getRandomIntInclusive(0, 2159), getRandomIntInclusive(0, 1079));
current_marker=L.marker(mizar).addTo(map).bindTooltip("I am OK");
};
//for(var j=0; j<10; j++){
setTimeout("del_add()", 100);
//};
//alert("done");
// var travel = L.polyline([sol, deneb]).addTo(map);
</script>

Change
setTimeout("del_add()", 100);
To
setTimeout(del_add, 100);
Firstly setTimetout takes two arguments, first one is function (not a string as in your example) and second one is time in ms.
If you just removed the quotes it would immediately trigger the function. It would be equivalent to this:
setTimetou(det_all(), 100);
// Equivalent to:
const foo = det_all();
setTimetou(foo, 100);
Wheres if you remove the round brackets you get equivalent to this
setTimetou(det_all, 100);
// Equivalent to:
setTimeout(() => det_all(), 100);
And this is what you need!
As I said setTimeout takes fucntion. If you wrinte foo() you immediately invoke the function and with combination with setTimeout(foo()) you are passing the result of the function to the setTimetou instead of the function itself

Related

Detect when marker crosses waypoint radius

I'm animating a marker along a route with waypoints and I am trying to detect when the marker reaches/ crosses a waypoint.
I've managed to get the animation part but seems to fail on the detections
here is my code
I'm creating the route
p = data.map(function(o){ return o.steps.map(function(g) { return g.geometry.coordinates }) });
const locations = p.reduce(function(arr, val){
arr = arr.concat(val); return arr ;
}, [] ),
route = new MultiLineString(locations);
I get the waypoints
intersections = data.reduce(function(s,c){ s=(!s?[]:s); return s = s.concat(c.steps.reduce(
function(e,a){
e = (!e? [] : e);
e.push(a.maneuver.location);
return e; },[])); return s;
},[]),
I create an extent from the waypoint on "right arrow click"
waypoint = fromLonLat(intersections[0])
.concat(fromLonLat(intersections[1]));
Then trying to detect when the marker is animated pass the waypoint
function moveFeature(event) {
const speed = 60;
const time = event.frameState.time;
const elapsedTime = time - lastTime;
distance = (distance + (speed * elapsedTime) / 1e6) % 2;
lastTime = time;
const currentCoordinate = route.getLineString(distance).getCoordinateAt(distance);
if(isNaN(currentCoordinate[0]) || (distance > 1) || Extent.containsCoordinate(waypoint, currentCoordinate) ) return stopAnimation();
position.setCoordinates(currentCoordinate);
const vectorContext = getVectorContext(event);
vectorContext.setStyle(styles.geoMarker);
vectorContext.drawGeometry(position);
map.getView().setCenter(currentCoordinate);
map.render();
}
But it doesn't seem to be true. Is there another way I can detect when the marker is past a certain point/ radius ?
Unless movefeature stops exactly on the extent Extent.containsCoordinate will not return true and the animation will continue past the point. It would be better to calculate the distance (or fraction of total distance) to the waypoint and stop when that is reached
const nearest = route.getClosestPoint(waypoint);
const partCoordinates = [];
route.forEachSegment(function(start, end){
partCoordinates.push(start.slice());
if (new LineString([start, end]).intersectsCoordinate(nearest)) {
partCoordinates.push(nearest);
return true;
}
});
const fraction = new LineString(partCoordinates).getLength() / route.getLength();

How to trigger a function repeatedly

I am working on a randomising function for a game in javascript and jquery. I have written this to randomise the position of a square in a 8x8x64px grid, and give the player a point when their character moves over it. The function works once, but wont repeat.
The relevant script
Every time the player moves it searches for
if (xNum==ptX && yNum==ptY) {
getPoint();
pointRand();
}
yNum and xNum is the player's coordinates and ptY and ptX is the point's. Movement occurs on keyUp for the arrow keys, and the if is also executed then.
Corresponding functions
//Score
var ptAllow = true;
var pt = 0;
var ptX = 7;
var ptY = 7;
var yPt = ptX*64+"px";
var xPt = ptY*64+"px";
function getPoint() {
if (ptAllow == true) {
pt++;
document.getElementById("scoreCounter").innerHTML = "score: "+pt;
document.getElementById("scoreFin").innerHTML = "score: "+pt;
}
}
function pointRand() {
ptX = Math.floor(Math.random() * 8) + 1;
ptY = Math.floor(Math.random() * 8) + 1;
ptX--;
ptY--;
yPt = ptX*64+"px";
xPt = ptY*64+"px";
$("#point").animate({"left": xPt, "top": yPt}, 100);
}
Like I said, It works perfectly the first time you move over a point, but after that nothing happens. . ptAllow is set to false once the player hits an obstacle, and the game is over.
Edit: There are no errors in the browser console, and the reason for adding and subtracting in pointRand() is that math.floor does not seem to work with a lowest value of zero.

Thousand separator in a JavaScript counter

I have this counter JavaScript snippet:
var START_DATE = new Date("October 24, 2015 11:00:00"); // start
var INTERVAL = 1; // sec
var START_VALUE = 0; // init value
var INCREMENT = 0.13; // value per sec
var count = 0;
window.onload = function()
{
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval,10) * INCREMENT + START_VALUE;
document.getElementById('count').innerHTML = count.toFixed(2);
setInterval("count += INCREMENT; document.getElementById('count').innerHTML = count.toFixed(2);", msInterval);
}
The counter may eventually display values in thousands and millions. My question is how to separate the thousands with a comma/blank space? I tried to achieve this via CSS, but apparently the options available here are not very practical. I was wondering on a possible solution in JavaScript. I found this on jsfiddle, but I am not sure how to apply it on the result of the counter?
function addCommas(n){
var rx= /(\d+)(\d{3})/;
return String(n).replace(/^\d+/, function(w){
while(rx.test(w)){
w= w.replace(rx, '$1,$2');
}
return w;
});
}
You can use javascript's built in toLocaleString function. Here is an example from MDN
var number = 3500;
console.log(number.toLocaleString()); // Displays "3,500" if in U.S. English locale
There are some additional options you can use with that function, but they are not all supported by various browsers. Basic use should work though.

Can I have a setTimeout inside a handler of another setTimeout?

Here's a quick (broke) jsfiddle: http://jsfiddle.net/wH2qF/
This isn't working for some reason... is it because I have a setTimeout inside a handler of another setTimeout?
$(function() {
$("#Volume").click(function() {
setTimeout(triggerVolumeChange, 4000);
function triggerVolumeChange()
{
var volumeDiv = document.getElementById("volumeNumber");
var volumeOld = 8;
var volumeNew = 37;
var timeNew = (1000/(volumeNew-volumeOld));
changeVolume();
function changeVolume()
{
volumeDiv.innerHTML = volumeOld;
volumeOld++;
if (volumeOld <= volumeNew) setTimeout(changeVolume, timeNew);
};
});
});
Should specify that for clarity purposes I deleted other things from that Click function, and also to clarify what doesn't work exactly, well, basically, I click and nothing happens, whereas if I cut out this chunk of code it works fine... actually the setting of the vars also work fine (naturally I presume) but when I paste or uncomment the changeVolume() function then the click stops working again... Any thoughts?
--
Another piece of clarification: What I'm trying to do is, on click, simulate the volume going from value 8 to 37, in a string.. thus the setTimeout inside that function.
--
As per your guy's request, here's the entire code... I doubt it will make sense, but here it is... FYI, on click this will trigger a number of animations to simulate the flow of an application I'm designing..
<script>
$(function() {
$("#Volume").click(function() {
var userPrompt = document.getElementById("userPrompt")
userPrompt.innerHTML = "Change volume to 37";
var avatarIcon = document.getElementById("avatarIcon");
avatarIcon.innerHTML = "<img src='imgs/haloIcons-volume_82x76.png' alt='Volume'/>";
var hints = document.getElementById("hints");
hints.style.opacity = 0;
$(".dragonTvOut").toggleClass("dragonTvIn");
setTimeout(triggerP, 1000);
function triggerP()
{
var halo = document.getElementById('avatar');
if( 'process' in halo ) {
halo.process();
};
};
setTimeout(triggerUserPrompt, 2000);
function triggerUserPrompt()
{
document.getElementById("userPrompt").className = "userPromptIn";
};
setTimeout(triggerVolumeChange, 4000);
function triggerVolumeChange()
{
document.getElementById("userPrompt").className = "userPromptEnd";
var halo = document.getElementById('avatar');
if( 'resume' in halo ) {
halo.resume();
}
document.getElementById("avatarIcon").className = "avatarIconEnd";
var volumeDiv = document.getElementById("volumeNumber");
var volumeOld = 8;
var volumeNew = 37;
var timeNew = (1000/(volumeNew-volumeOld));
changeVolume();
function changeVolume()
{
volumeDiv.innerHTML = volumeOld;
volumeOld++;
if (volumeOld <= volumeNew) setTimeout(changeVolume, timeNew);
}​;
var side = 100;
var paper = new Raphael(volumeArcAnim, 100, 300);
paper.customAttributes.arc = function (xloc, yloc, value, total, R) {
var alpha = 360 / total * value,
a = (90 - alpha) * Math.PI / 180,
x = xloc + R * Math.cos(a),
y = yloc - R * Math.sin(a),
path;
if (total == value) {
path = [
["M", xloc, yloc - R],
["A", R, R, 0, 1, 1, xloc - 0.01, yloc - R]
];
} else {
path = [
["M", xloc, yloc - R],
["A", R, R, 0, +(alpha > 180), 1, x, y]
];
}
return {
path: path
};
};
var arcWidth = 87;
var strokeRadius = arcWidth/2;
var indicatorArc = paper.path().attr({
"stroke": "#ffffff",
"stroke-width": 3,
arc: [side/2, side/2, 12, 100, strokeRadius]
});
indicatorArc.animate({
arc: [side/2, side/2, 60, 100, strokeRadius]
}, 1500, "<>", function(){
// anim complete here
});
};
});
});
</script>
Yes, you can have a setTimeout() inside another one -- this is the typical mechanism used for repeating timed events.
The reason yours isn't working is not to do with the setTimeout() itself; it's to do with the way you've nested the functions.
The changeVolume() function being inside triggerVolumeChange() means that you can't reference it directly using its name.
The quickest solution for you would be to remove the nesting, so that changeVolume() is at the root level rather than nested inside triggerVolumeChange().
You're missing an }:
$(function() {
$("#Volume").click(function() {
setTimeout(triggerVolumeChange, 4000);
function triggerVolumeChange()
{
var volumeDiv = document.getElementById("volumeNumber");
var volumeOld = 8;
var volumeNew = 37;
var timeNew = (1000/(volumeNew-volumeOld));
changeVolume();
function changeVolume()
{
volumeDiv.innerHTML = volumeOld;
volumeOld++;
if (volumeOld <= volumeNew) setTimeout(changeVolume, timeNew);
};
} // that one was missing
});
});
In your broken example http://jsfiddle.net/wH2qF/ there are a few problems
You forgot to tell jsfiddle to use jQuery
The id of the volume span (in JS) was ph but should be volumeNumber (as in the HTML)
Click here to see a working version
Had you selected jQuery from the libraries in jsfiddle, you would have seen an error
Uncaught TypeError: Cannot set property 'innerHTML' of null
That leads me to believe that your jsfiddle is not a good representation of your problem. Maybe try to create another reduction since the one you added only had "silly" errors?
If you don't want to use setInterval(), you can make the code work with these changes:
$(function() {
$("#Volume").click(function() {
setTimeout(triggerVolumeChange, 4000);
function triggerVolumeChange () {
var volumeDiv = document.getElementById("volumeNumber");
var volumeOld = 8;
var volumeNew = 37;
var timeNew = (1000/(volumeNew-volumeOld));
var changeVolume = function () {
volumeDiv.innerHTML = volumeOld;
volumeOld++;
if (volumeOld <= volumeNew) setTimeout(changeVolume, timeNew);
};
changeVolume();
}
});
});
Working demo at jsFiddle.
Technically there is no difference where the timer is initiated from. In most cases it is implemented as list of the timers with an identifiers and associated callback handlers.
So it will be ok if your logic is correct. There is no unpredictable conditions that bring infinite call sequences, and there is no infinite amount of timeout instances and so on.
For example imitation of setInterval function:
// Bad (unexpected multiple sequences started per each event)
const handler = () => {
setTimeout(handler)
}
<Button onClick={handler} />
// Good (previous interval closed before start new one)
const [id, idUpdate] = useState(-1)
const handler = () => {
const id = setTimeout(handler)
idUpdate(id)
}
const start = () => {
if(id !===-1) clearTimeout(id)
idUpdate(-1)
handler()
}
<Button onClick={start} />
or some else
// Bad (infinite events with small time will take all cpu time)
const handler = () => {
setTimeout(handler, 0) // actually mean several ms
}
// Good (special condition for finish iterations)
let count = 20
const handler = () => {
if(!count) return
count--
setTimeout(handler, 0)
}

How to hide/show multiple square at different time

I'm still struggling with my simple javascript game. Here is my previous question: Simple javascript game, hide / show random square
Some square show and hide randomely for a few seconds and you have to click on them. I use RaphaelJS to draw the square and a few of JQuery ($.each() function)
I can't make the hide/show with the setInterval working for each square. The function made by Mishelle looks good but I get a "This is not a function" error.. I've test different stuff but it's not as obvious as I thought :/
window.onload = function() {
var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
// random function to for the x and y axis of the square
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var rectanglemain = paper.rect(0, 0, 500, 500).attr({fill: "white",});
var win_click = 0; // set the var to count the click on the square
var recs = [];
for(var i = 0; i < 50; i++) {
var x = random(1,450);
var y = random(1,450);
var rec = paper.rect(x, y, 50, 50).attr({fill: 'blue'});
recs.push(rec); // add the square in an array
recs[i].click(function () {
//counting the clicks
win_click = win_click + 1;
})
function hideSquare() {recs[i].hide();}
hideSquare();
}
rectanglemain.click(function () {
alert('you click on ' + win_click + ' squares');
});
/* here is a function made by Mishelle on my previous question, unfortunately I can't make it work (this is not a function error).
function showBriefly (timeFromNow, duration) {
window.setTimeout(this.rec.show, timeFromNow);
window.setTimeout(this.rec.hide, timeFromNow + duration);
}
recs[2].showBriefly(1000, 3000); to test the function
*/
}
Thanks for the help :)
try
window.setTimeout(function(){this.rec.show();}, timeFromNow )
Just came across your problem, just in case you read this and you want to know what was the problem. this is undefined within the callback, thus you need to store which rectangle you were referring to in a variable (I've called it square), see my code:
showBriefly: function(timeFromNow, duration) {
square = this.box;
setTimeout(function(){square.show();}, timeFromNow )
setTimeout(function(){square.hide();}, timeFromNow + duration )
}
Cheers

Categories

Resources