简体   繁体   English

javascript setInterval()

[英]javascript setInterval()

I have this code: 我有以下代码:

function noti() {
     document.title = document.title + " 1"
}

setInterval("noti()", 1000)

The problem is it outputs: 问题是它输出:

My title 1 1 1 1 1 1 1 ..... to infinite.... 1 我的头衔1 1 1 1 1 1 1 .....到无穷.... 1

Is there any possible way to output this as "My title 1" 有没有可能将其输出为“我的标题1”的方法

the noti() function serves as a purpose when everytime an update occurs in the database, whatever is the length gathered from the database it will be outputed into the users title bar . 每当数据库中发生更新时, noti()函数便会用作目的, 无论从数据库中收集到的长度如何 ,都会将其输出到用户标题栏中

So, "My title 1", where "My title" is the name of the user and "1" the length coming from the database 因此,“我的标题1”,其中“我的标题”是用户名,“ 1”的长度来自数据库

If you want to execute noti only once, you should be using setTimeout , not setInterval . 如果只执行一次noti ,则应使用setTimeout ,而不要使用setInterval

Update: OK, so you want to execute noti continuously but replace the suffix instead of adding it anew each time. 更新:好的,因此您想连续执行noti但是替换后缀而不是每次都重新添加。 Do this with a regular expression replace: 用正则表达式替换:

document.title = document.title.replace(/(\b\s*\d+)?$/, " " + num);

See it in action . 看到它在行动

Typically something like this is tagged. 通常,类似这样的标签。 Usually you'll see something like (1) My title . 通常,您会看到类似(1) My title

In this case it's a simple matter: 在这种情况下,这很简单:

function noti(num) { // num is the number of notifications
    document.title = document.title.replace(/^(?:\(\d+\) )?/,"("+num+") ");
}

try: 尝试:

var ttl = document.title; //initalize title
function noti() {
  document.title = ttl + " 1";
  //if you want to continue setting the title 
  //(so periodically repeat setting document.title) 
  //uncomment the following:
  //setTimeout(noti, 1000);
}

//use a function reference here. 'noti()' will
//cause the interpreter to do an eval
setTimeout(noti, 1000); 

See why you shouldn't use setInterval 看看为什么不应该使用setInterval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM