Dasmond Miles Dasmond Miles - 1 year ago 68
jQuery Question

How to start and stop checking a condition every few minutes in javascript?

I am developing a javascript application where I have to do this.

  1. Check every 5 seconds that whether the page contains an element with tag.

  2. Once, the tag is detected, then start my video tracking function.

  3. 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:

setInterval(function() {
var myVideo = document.getElementsByTagName('video')[0];

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);

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.

Answer Source

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) {
}, 5000);

I hope that helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download