Reputation: 193
I am developing a javascript application where I have to do this.
Check every 5 seconds that whether the page contains an element with tag.
Once, the tag is detected, then start my video tracking function.
DO NOT check again every 5 seconds that whether the page contains an element with tag - once a tag has been detected and my video tracking function has been started.
Here is my code:
<script>
setInterval(function() {
var myVideo = document.getElementsByTagName('video')[0];
console.log(myVideo);
if (myVideo != null)
{
myVideo.id = 'video-stream';
var colors = new tracking.ColorTracker(['magenta', 'cyan', 'yellow']);
colors.on('track', function(event) {
if (event.data.length === 0) {
// No colors were detected in this frame.
} else {
event.data.forEach(function(rect) {
console.log(rect.x, rect.y, rect.height, rect.width, rect.color);
});
}
});
tracking.track("#video-stream", colors);
}
}, 5000);
</script>
Right now, it just keeps checking even if a tag is detected, So how do I stop it from checking once it if (myVideo != null)
condition is fulfilled and it has gotten into it?
Any suggestions will be highly appreciated.
Upvotes: 0
Views: 1437
Reputation: 2825
You should define your interval in variable and when you detect the video you should use clearInterval()
https://jsfiddle.net/o127oqjr/
var myInterval = setInterval(function() {
var myVideo = document.getElementsByTagName('video')[0];
console.log(myVideo);
if (myVideo != null)
{
clearInterval(myInterval);
myVideo.id = 'video-stream';
var colors = new tracking.ColorTracker(['magenta', 'cyan', 'yellow']);
colors.on('track', function(event) {
if (event.data.length === 0) {
// No colors were detected in this frame.
} else {
event.data.forEach(function(rect) {
console.log(rect.x, rect.y, rect.height, rect.width, rect.color);
});
}
});
tracking.track("#video-stream", colors);
}
else{
console.log('notFound')
}
}, 5000);
Upvotes: 1
Reputation: 2672
The setInterval
function returns a value with you can then use to stop the interval in conjunction with clearInterval
, so in your case:
var interval = setInterval(function() {
...
if (myVideo !== null) {
clearInterval(interval)
}
...
}, 5000);
I hope that helps.
Upvotes: 4
Reputation: 35680
Create a function, which calls itself after 5s if the tag doesn't exist:
function testVideo() {
var myVideo = document.getElementsByTagName('video')[0];
console.log(myVideo);
if (myVideo != null) {
myVideo.id = 'video-stream';
var colors = new tracking.ColorTracker(['magenta', 'cyan', 'yellow']);
colors.on('track', function(event) {
if (event.data.length === 0) {
// No colors were detected in this frame.
} else {
event.data.forEach(function(rect) {
console.log(rect.x, rect.y, rect.height, rect.width, rect.color);
});
}
});
tracking.track("#video-stream", colors);
}
else {
setTimeout(test, 5000); //try again in 5s
}
} //testVideo
testVideo(); //call the function
Upvotes: 1