我有一个函数,它会在按下按钮后每两秒连续生成一个值。
如果按钮单击2次,则生成2值,依此类推。
我在第二次点击时使用clearInterval
,依此类推以避免重复值。
var clickValue = 0;
function func() {
var value = 0;
var generateValue = function() {
value = value + 1;
console.log('value: ' + value);
}
var startInterval = setInterval(generateValue, 2000);
clickValue = clickValue + 1;
console.log(clickValue + ' click');
if (clickValue > 1) {
clearInterval(startInterval);
console.log('Interval on ' + clickValue + ' click cleared');
}
}
<button onclick="func()">Click</button>
如果我们运行上面的代码,它只是清除第二个间隔,依此类推。第一个间隔的值仍在运行。
我预期的结果:
1 click
value: 1
value: 2
value: 3
2 click
Interval on 1 click cleared
value: 1
value: 2
value: 3
3 click
Interval on 2 click cleared
value: 1
value: 2
value: 3
如何在第二次点击后清除第一个间隔值并开始第二个间隔值,依此类推上面的结果?
答案 0 :(得分:1)
尝试类似
的内容 /// <summary>
/// upload file to Document Library
/// </summary>
/// <param name="context"></param>
/// <param name="documentLibraryName">MyDocLib</param>
/// <param name="filePath">C:\\</param>
/// <param name="fileName">hello2.txt</param>
public static void uploadFile(ClientContext context, string documentLibraryName, string filePath, string fileName)
{
string siteURL = context.Url.EndsWith("/") ? context.Url.Substring(0, context.Url.Length - 1) : context.Url;
List list = context.Web.Lists.GetByTitle(documentLibraryName);
context.Load(list);
context.ExecuteQuery();
FileStream fileStream = new FileStream(filePath, FileMode.Open);
FileCreationInformation newFileInfo = new FileCreationInformation()
{
ContentStream = fileStream,
Url = siteURL + "/" + documentLibraryName + "/" + fileName,
Overwrite = true
};
Microsoft.SharePoint.Client.File file = list.RootFolder.Files.Add(newFileInfo);
context.Load(file);
context.ExecuteQuery();
}
此处每次点击的价值都是新的。
答案 1 :(得分:0)
var clickValue = 0;
var value = 0;
var startInterval;
function func() {
var generateValue = function() {
value = value + 1;
console.log('value: ' + value);
}
startInterval = setInterval(generateValue, 2000);
clickValue = clickValue + 1;
console.log(clickValue + ' click');
if (clickValue > 1) {
clearInterval(startInterval);
console.log('Interval on ' + (clickValue-1) + ' click cleared');
value = 0;
}
}
<button onclick="func()">Click</button>
答案 2 :(得分:0)
var clickValue = 0;
var lastId = null;
function func() {
// clear last interval
clearInterval(lastId);
console.log('Interval on ' + clickValue + ' click cleared')
clickValue++;
console.log(clickValue + ' click');
// start new interval
var value = 0;
lastId = setInterval(function () {
value++;
console.log('value: ' + value);
}, 2000)
}
<button onclick="func()">click</button>